Check if a timestamp/date is today in JavaScript


Check if a timestamp/date is today in JavaScript

In this article, we will determine if a given date is equal to today's date or not using JavaScript.

To get the date, month and the year of a date instance in Javascript, we can use the getDate(),getMonth() and getFullYear() method. This method helps extract each part from a date and helps in comparison.

Example:

const today = new Date();
console.log(today.getDate()); //2
console.log(today.getMonth()); //8
console.log(today.getFullYear()); //2022

Now using these methods, let's create a function that will take a date as an argument and compare it with the current date (today's date values).

If the given date and today's date are equal it will return true, else it will return false.

const isToday = (givenDate) => {
  const date = new Date(givenDate)
  const today = new Date()
  
  return date.getDate() == today.getDate() &&
    date.getMonth() == today.getMonth() &&
    date.getFullYear() == today.getFullYear()
}


console.log(isToday('2022-08-01')) //false
console.log(isToday('2022-09-02')) //true

Here, we have created a function isToday(), which takes the date as an argument.

We have passed the date string (eg 2022-09-02) in ISO Date format (YYYY-MM-DD) to the function.

In the function, we have converted the given string into a valid Date object using new Date(givenDate). It is needed so that we can apply the getDate() , getMonth() functions on it.

Note: If we don't convert the string to a valid date, it will give us an error like getDate() is not a function.

Once we have converted the given date. We get today's date using new Date().

Next, we just compare the date, month, and year of both the date object using == (equality operator) and && (Logical AND operator).

If the dates are the same, it will return true, if not, the function will return false.


Related Topics:

date.getDate() is not a function error in JavaScript

JavaScript - Get Month Name from Date

Add Days to a Date in JavaScript with Example

Get Tomorrow's Date using JavaScript - Quick Way

Get Current Date in Different Date Formats in JavaScript

Get Yesterday date in JavaScript

Convert date to long date format using Javascript