Comparing date part only without comparing time in JavaScript

后端 未结 22 1862
春和景丽
春和景丽 2020-11-22 10:59

What is wrong with the code below?

Maybe it would be simpler to just compare date and not time. I am not sure how to do this either, and I searched, but I couldn\'t

22条回答
  •  我在风中等你
    2020-11-22 11:32

    I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.

    For example,

    date1 = new Date()
    date2 = new Date(2011,8,20)
    

    date2 will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:

    date1.setHours(0,0,0,0)
    

    Now you can compare the two dates as DATES only without worrying about time elements.

提交回复
热议问题