How to compare the date part alone from a date time value

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

I have two variables namely

date1 = Mon Nov 25 2013 00:00:00 GMT+0530 (IST) date2 = Mon Nov 25 2013 14:13:55 GMT+0530 (IST)

When I compare the two dates I get that date2 is greater which I need is correct. But I do not want to check the time part of the two dates I have. How could I get the date part alone from these two dates and compare it?

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); }

回答1:

Try clearing the time using

Date.setHours(hour,min,sec,millisec)

Code:

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); }


回答2:

The best way would be to modify the accepted answer's if statement as follows

if(d.setHours(0,0,0,0) >= today.setHours(0,0,0,0))

In this way, you can easily check for equality as well because the return type for setHours() is integer.



回答3:

Try:

    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);     }


回答4:

     var StartDate = $("#StartDate").val();        var EndDate = $("#EndDate").val();        if ((( EndDate - StartDate)/ (86400000*7))<0)        {         alert("Start Date Must Be Earlier Than End Date"); $("#StartDate").focus();          error = true;          return false;        }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!