how to check if a date is today

How to Check If a Date Is Today in JavaScript

In this short tip post, we will learn how to find out if a Date object represents a today DateTime.

Objective

To determine if a JavaScript Date object instance is a representation of a date/time that is “today”.

Approach

By using a JavaScript Date instance, we can use the
getDate(), getMonth() and getFullYear() methods, which return the day, month and year of a date, and compare them to today’s date, which we can fetch using new Date().

Code

Here is the code:

function isToday(dateParameter) {
        var today = new Date();
        return dateParameter.getDate() === today.getDate() && dateParameter.getMonth() === today.getMonth() && dateParameter.getFullYear() === today.getFullYear();
}

console.log("Is today ? ", isToday(new Date())); // true
console.log("Is today ? ", isToday(new Date('10-11-2014'))); // false

Check out the codepen for a live demo of the code.

See the Pen
Is date today?
by Shahid Shaikh (@codeforgeek)
on CodePen.

Love JavaScript? Learn more about it here.

Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Related Posts

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.