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

后端 未结 5 1478
北荒
北荒 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: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.

提交回复
热议问题