如何仅从日期时间值比较日期部分

Out*_*ker 32 javascript jquery

我有两个变量

date1 = Mon Nov 25 2013 00:00:00 GMT+0530 (IST)
date2 = Mon Nov 25 2013 14:13:55 GMT+0530 (IST)
Run Code Online (Sandbox Code Playgroud)

当我比较我得到的两个日期date2更大,我需要的是正确的.但我不想查看我所拥有的两个日期的时间部分.如何从这两个日期单独获取日期部分并进行比较?

var today = new Date();     //Mon Nov 25 2013 14:13:55 GMT+0530 (IST) 
d = new Date(my_value);     //Mon Nov 25 2013 00:00:00 GMT+0530 (IST) 
if(d>=today){               //I need to check the date parts alone.
    alert(d is greater than or equal to current date);
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*een 59

尝试使用Date.setHours以下方式清除时间

dateObj.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])
Run Code Online (Sandbox Code Playgroud)

示例代码:

var today = new Date();
today.setHours(0, 0, 0, 0);
d = new Date(my_value); 
d.setHours(0, 0, 0, 0);

if(d >= today){ 
    alert(d is greater than or equal to current date);
}
Run Code Online (Sandbox Code Playgroud)

  • @Outlooker *仅供参考* [您不能使用 == 进行日期比较](http://stackoverflow.com/questions/20162435/javascript-compare-two-dates-to-get-a-difference/20162708#comment30055600_20162603) 。只是让你知道。 (3认同)

Sak*_*ham 10

最好的方法是修改接受的答案if声明,如下所示

if(d.setHours(0,0,0,0) >= today.setHours(0,0,0,0))
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以轻松检查相等性,因为返回类型为setHours()整数.


Igl*_*gle 6

尝试:

    var today = new Date();     //Mon Nov 25 2013 14:13:55 GMT+0530 (IST) 
    var d = new Date(my_value);     //Mon Nov 25 2013 00:00:00 GMT+0530 (IST) 
    var todayDateOnly = new Date(today.getFullYear(),today.getMonth(),today.getDate()); //This will write a Date with time set to 00:00:00 so you kind of have date only
    var dDateOnly = new Date(d.getFullYear(),d.getMonth(),d.getDate());

    if(dDateOnly>=todayDateOnly){               
        alert(d is greater than or equal to current date);
    }
Run Code Online (Sandbox Code Playgroud)