Check if a Date is Today's date using JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 29, 2022

banner

Photo from Unsplash

Check if a Date is Today's date using JavaScript #

To check if a date is today's date:

  1. Use the Date() constructor to get today's date.
  2. Use the toDateString() method to compare the two dates.
  3. If the method returns 2 equal strings, the date is today's date.
index.js
function isToday(date) { const today = new Date(); // 👇️ Today's date console.log(today); if (today.toDateString() === date.toDateString()) { return true; } return false; } console.log(isToday(new Date())); // 👉️ true console.log(isToday(new Date('2022-01-21'))); // 👉️ false

We used the Date() constructor to get the current date.

The next step is to compare the current date to the supplied date, ignoring the time.

The toDateString method returns the date portion of a Date object in human-readable form.

index.js
// 👇️ Tue Jan 25 2022 console.log(new Date().toDateString());

If the method returns the same string for the current date and the passed in date, then the supplied date is today's date.

It is very important to ignore the hours, minutes, seconds and milliseconds when comparing the two dates because if you don't, you'd be comparing a date to a specific moment in time.

Alternatively, you could use a more explicit approach.

To check if a date is today's date:

  1. Use the Date() constructor to get today's date.
  2. Compare the output of the getFullYear(), getMonth() and getDate() methods for the dates.
  3. If the year, month and day values are equal, then the date is today's date.
index.js
function isToday(date) { const today = new Date(); // 👇️ Today's date console.log(today); if ( today.getFullYear() === date.getFullYear() && today.getMonth() === date.getMonth() && today.getDate() === date.getDate() ) { return true; } return false; } console.log(isToday(new Date())); // 👉️ true console.log(isToday(new Date('2022-01-21'))); // 👉️ false

The function makes use of the following 3 date-related methods:

  • Date.getFullYear method - returns a four-digit number representing the year that corresponds to a date.

  • Date.getMonth - returns an integer between 0 (January) and 11 (December) and represents the month for a given date. Unfortunately, the getMonth method is off by 1.

  • Date.getDate - returns an integer between 1 and 31 representing the day of the month for a specific date.

If the year, month and day of the month values for the current date are equal to the values for the supplied date, then the date is today's date.

Which approach you pick is a matter of personal preference. I'd go with the toDateString method, as it is more concise and just as readable.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.