How to check if a date is today or the current date in JavaScript?

April 16, 2021 - 2 min read

To check if a date is today or the current date, we check the day, month, and year of that date with the current date's using the getDate(), getMonth(), and getYear() methods from the Date object in JavaScript.

TL;DR

// Function to check if a date is today or not
function isDateToday(date) {
  const otherDate = new Date(date);
  const todayDate = new Date();

  if (
    otherDate.getDate() === todayDate.getDate() &&
    otherDate.getMonth() === todayDate.getMonth() &&
    otherDate.getYear() === todayDate.getYear()
  ) {
    return true;
  } else {
    return false;
  }
}

For example, let's imagine we have a date of 18 July 2020 (this is a valid date string or you can pass any valid date string) and we want to check if this date is the current date. So let's pass this date string to the Date() constructor to make it into a Date object.

It can be done like this,

const otherDate = new Date("18 July 2020"); // Valid Date string

Now let's get the current date using creating a new Date object like this,

const otherDate = new Date("18 July 2020"); // Valid Date string
const todayDate = new Date();

Now, all we need is to check whether the day, month and year of both dates match with each other.

It can be done like this,

const otherDate = new Date("18 July 2020"); // Some other date
const todayDate = new Date(); // Current or today's date

// Check if the other date matches today's date
if (
  otherDate.getDate() === todayDate.getDate() &&
  otherDate.getMonth() === todayDate.getMonth() &&
  otherDate.getYear() === todayDate.getYear()
) {
  console.log("The date is today!");
} else {
  console.log("The date is not today!");
}

See the above code live in JSBin.

That's all! 😃

If you want the whole code as a utility function here it is,

// Function to check if a date is today or not
function isDateToday(date) {
  const otherDate = new Date(date);
  const todayDate = new Date();

  if (
    otherDate.getDate() === todayDate.getDate() &&
    otherDate.getMonth() === todayDate.getMonth() &&
    otherDate.getYear() === todayDate.getYear()
  ) {
    return true;
  } else {
    return false;
  }
}

Feel free to share if you found this useful 😃.