Javascript中的日期变量问题 [英] issue with date variable in Javascript

查看:139
本文介绍了Javascript中的日期变量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var dt_from = "2013/05/25";
var dt_to   = "2013/05/25";

if(dt_from == dt_to)
{
    alert("Both dates are Equal!");
}
else if(dt_from > dt_to)
{
    alert("From date should not be greater than todate!");
}
else if(dt_from < dt_to)
{
    alert("Okay!");
}

上述代码工作正常。但以下代码无效:

The above Code is working fine. But the following code is not working:

var dt_from = new Date("2013/05/25");
var dt_to   = new Date("2013/05/25");

if(dt_from === dt_to)
{
    alert("Both dates are Equal!");
}
else if(dt_from > dt_to)
{
    alert("From date should not be greater than todate!");
}
else if(dt_from < dt_to)
{
    alert("Okay!");
}

if(dt_from === dt_to)无法使用上述代码。任何想法?

This if(dt_from === dt_to) is not working with the above code. Any Idea?

推荐答案

您正在将对象引用与 == 进行比较。虽然它们可能代表相同的日期时间,但它们是不同的对象。使用< / > 可以将对象转换为数字(自纪元以来的毫秒数),然后进行比较。如果要测试相等性,则必须手动强制转换:

You are comparing object references with ==. While they may represent the same datetime, they are distinct objects. Using </> works as it casts the objects to numbers (milliseconds since epoch) which are then compared. If you want to test on equality, you have to force that conversion manually:

dt_from.getTime() == dt_to.getTime() // most explicit
// or
+dt_from == +dt_to // shortest
dt_from - dt_to == 0  // equivalent…
dt_from.valueOf() == dt_to.valueOf()
Number(dt_from) == Number(dt_from)

这篇关于Javascript中的日期变量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆