What is the best way to determine if a date is today in JavaScript?

后端 未结 5 1474
北荒
北荒 2020-12-05 23:32

I have a date object in JavaScript and I want to figure out if that date is today. What is the fastest way of doing this?

My concern was around comparing date object

相关标签:
5条回答
  • 2020-12-05 23:45

    If both are Date() objects, you can use this to 'format' the date in a way that it will only compare on the year/month/day: if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0));

    Nearly identical question: How to check if input date is equal to today's date?

    0 讨论(0)
  • 2020-12-05 23:50

    The answers based on toDateString() will work I think, but I personally would avoid them since they basically ask the wrong question.

    Here is a simple implementation:

    function areSameDate(d1, d2) {
        return d1.getFullYear() == d2.getFullYear()
            && d1.getMonth() == d2.getMonth()
            && d1.getDate() == d2.getDate();
    }
    

    MDN has a decent overview of the JS Date object API if this isn't quite what you need.

    0 讨论(0)
  • 2020-12-05 23:52

    You could use toDateString:

    var d = new Date()
    var bool = (d.toDateString() === otherDate.toDateString());
    
    0 讨论(0)
  • 2020-12-06 00:03

    I prefer to use moment lib

    moment('dd/mm/yyyy').isSame(Date.now(), 'day');
    
    0 讨论(0)
  • 2020-12-06 00:04
    var someDate = new Date("6 Dec 2011").toDateString();
    var today = new Date().toDateString();
    var datesAreSame = (today === someDate);
    
    0 讨论(0)
提交回复
热议问题