在 Javascript 中确定日期相等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4587060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:05:49  来源:igfitidea点击:

Determining Date Equality in Javascript

javascriptdateequality

提问by Jarred

I need to find out if two dates the user selects are the same in Javascript. The dates are passed to this function in a String ("xx/xx/xxxx").That is all the granularity I need.

我需要找出用户选择的两个日期在 Javascript 中是否相同。日期以字符串(“xx/xx/xxxx”)的形式传递给这个函数。这就是我需要的所有粒度。

Here is my code:

这是我的代码:

        var valid = true;
    var d1 = new Date($('#datein').val());
    var d2 = new Date($('#dateout').val());
    alert(d1+"\n"+d2);
    if(d1 > d2) {
        alert("Your check out date must be after your check in date.");
        valid = false;
    } else if(d1 == d2) {
        alert("You cannot check out on the same day you check in.");
        valid = false;
    }

The javascript alert after converting the dates to objects looks like this:

将日期转换为对象后的 javascript 警报如下所示:

Tue Jan 25 2011 00:00:00 GMT-0800 (Pacific Standard Time)

2011 年 1 月 25 日星期二 00:00:00 GMT-0800(太平洋标准时间)

Tue Jan 25 2011 00:00:00 GMT-0800 (Pacific Standard Time)

2011 年 1 月 25 日星期二 00:00:00 GMT-0800(太平洋标准时间)

The test to determine if date 1 is greater than date 2 works. But using the == or === operators do not change valid to false.

确定日期 1 是否大于日期 2 的测试有效。但是使用 == 或 === 运算符不会将 valid 更改为 false。

回答by spinon

Use the getTime()method. It will check the numeric value of the date and it will work for both the greater than/less than checks as well as the equals checks.

使用getTime()方法。它将检查日期的数值,并且适用于大于/小于检查以及等于检查。

EDIT:

编辑:

if (d1.getTime() === d2.getTime())

回答by devmiles.com

If you don't want to call getTime()just try this:

如果你不想打电话getTime()试试这个:

(a >= b && a <= b)

(a >= b && a <= b)

回答by Arjun Kubendran

var d1 = new Date($('#datein').val());
var d2 = new Date($('#dateout').val());

use two simple ways to check equality

使用两种简单的方法来检查相等性

  1. if( d1.toString() === d2.toString())
  2. if( +d1 === +d2)
  1. if( d1.toString() === d2.toString())
  2. if( +d1 === +d2)