Check if a date is today in JavaScript

Check if a date is today in JavaScript

How can you determine if a JavaScript Date object instance is a representation of a date/time that is “today” date?


Given a Date instance, we can use thegetDate(),getMonth() and  getFullYear() methods, which return the day, month and year of a date.


const date = new Date(2020, 3, 12);

date.getDate();
date.getMonth();
date.getFullYear();

The getDay() method returns the day of the week for the specified date according to the local time (0 corresponds to Sunday). To get the day of the month, use Date.prototype.getDate().

The getMonth() method returns the month of the entered date according to the local time. Dialing starts at 0 (i.e. 0 corresponds to the first month of the year).

The getFullYear() method returns the year of the date entered according to local time. This method must be used instead of getYear().

To check that a date is the current date, you just have to create this function which uses the 3 functions explained above. The function returns a boolean (true if the date is the same as the current date).


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

Here is an example of the function


const date = new Date(2020, 3, 12);
console.log(isToday(date)); // true

There is also an alternative version that allows you to extend the date object by directly adding the above function to the prototype object as shown below:


Date.prototype.isToday = function () {
    const today = new Date()
    return this.getDate() === today.getDate() &&
    this.getMonth() === today.getMonth() &&
    this.getFullYear() === today.getFullYear();
};

Example :


const date = new Date(2020, 3, 12);
console.log(date.isToday()); // true

Back to Javascript Section

Documentation Javascript

By ayed_amira

I'm a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming :)

Leave a comment

Your email address will not be published. Required fields are marked *