比较 JavaScript 日期
我将日期与这样的内容进行比较:
var dt = new Date();
dt.setDate("17");
dt.setMonth(06);
dt.setYear("2009");
var date = new Date();
console.log("dt(%s) == date(%s) == (%s)", dt, date, (dt == date) );
if( now == dt ) {
....
}
字符串值当然是动态的。
在日志中我看到:
dt(Fri Jul 17 2009 18:36:56 GMT-0500 (CST)) == date(Fri Jul 17 2009 18:36:56 GMT-0500 (CST) == (false)
我尝试了 .equals() 但它不起作用(我正在尝试 JavaScript 的 Java 部分:P)
如何比较这些日期以便它们返回 true?
I'm comparing dates with something like this:
var dt = new Date();
dt.setDate("17");
dt.setMonth(06);
dt.setYear("2009");
var date = new Date();
console.log("dt(%s) == date(%s) == (%s)", dt, date, (dt == date) );
if( now == dt ) {
....
}
The string values are dynamic of course.
In the logs I see:
dt(Fri Jul 17 2009 18:36:56 GMT-0500 (CST)) == date(Fri Jul 17 2009 18:36:56 GMT-0500 (CST) == (false)
I tried .equals() but it didn't work ( I was trying the Java part of JavaScript :P )
How can I compare these dates so they return true?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下代码应该可以解决您的问题:
问题是,当您编写:
...您实际上是在问“
myDate
是否指向myOtherDate
所指向的同一个对象”到?”,而不是“myDate
与myOtherDate
相同吗?”。解决方案是使用
getTime
获取表示 Date 对象的数字(并且由于getTime
返回自纪元时间以来的毫秒数,因此该数字将是一个精确的数字) Date 对象的表示),然后使用该数字进行比较(比较数字将按预期工作)。The following code should solve your problem:
The problem is that when you write:
...you're actually asking "Is
myDate
pointing to the same object thatmyOtherDate
is pointing to?", not "IsmyDate
identical tomyOtherDate
?".The solution is to use
getTime
to obtain a number representing the Date object (and sincegetTime
returns the number of milliseconds since epoch time, this number will be an exact representation of the Date object) and then use this number for the comparison (comparing numbers will work as expected).您的代码的问题是您正在比较时间/日期部分而不是仅比较日期。
尝试以下代码:
如果保留 for 循环代码(由“延迟代码 -start”标识),控制台将显示“false”,如果删除 for 循环代码,控制台将记录“true”,即使在这两种情况下都是 myDate是 7/17/2009,“现在”是 7/17/2009。
问题在于 JavaScript 日期对象同时存储日期和时间。 如果只想比较日期部分,则必须编写代码。
如果两个 javascript“日期部分”相等,忽略关联的时间部分,此函数将打印“true”。
The problem with your code is that you are comparing time/date part instead of only the date.
Try this code:
If you keep the for loop code (identified by 'Delay code -start'), console will show 'false' and if you remove the for loop code, console will log 'true' even though in both the cases myDate is 7/17/2009 and 'now' is 7/17/2009.
The problem is that JavaScript date object stores both date and time. If you only want to compare the date part, you have to write the code.
This function will print 'true' if the two javascript 'date part' is equal ignoring the associated time part.
(myDate == myOtherDate)
不起作用,它比较两个对象(指针)而不是它们包含的值。 使用 getTime 获取 Date 的整数表示形式,然后进行比较。(myDate == myOtherDate)
does not work, it compares the two objects (pointers) instead of the value that they contain. Use getTime to get integer representation of Date and then compare.