Javascript 如何知道日期是今天?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4292990/
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
How to know date is today?
提问by nacho4d
I am trying this but is not working... why?
我正在尝试这个但不起作用......为什么?
<html>
<body>
<script type="text/javascript">
var today=new Date(); //today is Nov 28, 2010
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
document.write(today+" ");
var today2 = new Date("November 28, 2010");
document.write(today2 + " ");
if (today == today2) { document.write("==");
if (!(today > today2) && !(today < today2) ) {document.write("== ");}
if (today > today2) { document.write("> ");}
if (today >= today2 ){ document.write(">= ");}
if (today < today2 ) { document.write("< ");}
if (today <= today2 ){ document.write("<= ");}
</script>
</body>
</html>
And I always get this:
我总是得到这个:
Sun Nov 28 2010 00:00:00 GMT+0900 (JST) Sun Nov 28 2010 00:00:00 GMT+0900 (JST) > >=
Aren't both dates to be the same? Hence, I should get ==
printed but is not happening... ;(
两个日期不一样吗?因此,我应该被==
打印出来,但没有发生...... ;(
Thank you for your help in advance.
提前谢谢你的帮助。
回答by user113716
They will never match because you're comparing two separate Date
object instances.
它们永远不会匹配,因为您正在比较两个单独的Date
对象实例。
You need to get some common value that can be compared. For example .toDateString()
.
您需要获得一些可以进行比较的通用值。例如.toDateString()
。
today.toDateString() == today2.toDateString(); // true
If you just compare two separate Date
objects, even if they have the exact same date value, they are still different.
如果您只是比较两个单独的Date
对象,即使它们具有完全相同的日期值,它们仍然是不同的。
For example:
例如:
today == new Date( today ); // false
They are the same date/time value, but are not the same object, so the result is false
.
它们是相同的日期/时间值,但不是相同的对象,因此结果是false
.
回答by user2619282
function today(td) {
var d = new Date();
return td.getDate() == d.getDate() && td.getMonth() == d.getMonth() && td.getFullYear() == d.getFullYear();
}