Comparing date part only without comparing time in JavaScript

后端 未结 22 1460
春和景丽
春和景丽 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:52

    Using Moment.js

    If you have the option of including a third-party library, it's definitely worth taking a look at Moment.js. It makes working with Date and DateTime much, much easier.

    For example, seeing if one Date comes after another Date but excluding their times, you would do something like this:

    var date1 = new Date(2016,9,20,12,0,0); // October 20, 2016 12:00:00
    var date2 = new Date(2016,9,20,12,1,0); // October 20, 2016 12:01:00
    
    // Comparison including time.
    moment(date2).isAfter(date1); // => true
    
    // Comparison excluding time.
    moment(date2).isAfter(date1, 'day'); // => false
    

    The second parameter you pass into isAfter is the precision to do the comparison and can be any of year, month, week, day, hour, minute or second.

提交回复
热议问题