Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 as one might have a different time than another but any time on today's date should return true.

like image 910
leora Avatar asked Dec 06 '11 00:12

leora


People also ask

How do you determine if a date is today in JavaScript?

To check if a date is today's date:Use the Date() constructor to get today's date. Use the toDateString() method to compare the two dates. If the method returns 2 equal strings, the date is today's date.

What is now () in JavaScript?

now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.

Which function object is used to display today's date?

Use new Date() to generate a new Date object containing the current date and time. This will give you today's date in the format of mm/dd/yyyy.


2 Answers

You could use toDateString:

var d = new Date() var bool = (d.toDateString() === otherDate.toDateString()); 
like image 99
Joseph Marikle Avatar answered Oct 12 '22 17:10

Joseph Marikle


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.

like image 30
recf Avatar answered Oct 12 '22 18:10

recf