确定Javascript中的日期平等 [英] Determining Date Equality in Javascript
问题描述
我需要找出用户选择的两个日期在Javascript中是否相同。日期被传递给一个String(xx / xx / xxxx)的这个函数,这就是我需要的所有粒度。
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.
这是我的代码: p>
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;
}
将日期转换为对象后的javascript警报如下所示:
The javascript alert after converting the dates to objects looks like this:
星期二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(太平洋标准时间)
Tue Jan 25 2011 00:00:00 GMT-0800 (Pacific Standard Time)
确定日期1是否大于日期2的测试工作。但是使用==或===操作符不会变为有效。
The test to determine if date 1 is greater than date 2 works. But using the == or === operators do not change valid to false.
推荐答案
使用 getTime()
方法。它将检查日期的数值,它将适用于大于/小于检查以及等于检查。
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.
编辑:
if (d1.getTime() == d2.getTime())
这篇关于确定Javascript中的日期平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!