Skip to Content

Determine if a Date is Today's Date Using JavaScript

This quick tutorial illustrates how to determine if a custom date object or string is today's date using the JavaScript Date object and the toDateString() method.

Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.

Is Date Today?

To run a match, we'll create a custom function that returns a boolean value. The function will return true if the dates match, and false if they don't:

function isToday(my_date) {
let today = new Date();

if (typeof(my_date) === "string") {
my_date = new Date(my_date);
}

return today.toDateString() == my_date.toDateString();
}

In our custom isToday() method, we're accepting a single argument, my_date, and creating a local variable, today, with today's date stored as the value.

We then use the typeof() function to determine if the date passed into our custom method is a date object or a string. If it's a string, we convert it to a date object.

Finally, we run a comparison between the two date objects using the toDateString() method and return whether they match or not.

You can either call this function with a date object:

var is_today = isToday(new Date());
// true

Or a string:

var is_today = isToday("01/01/2023");
// false

Conclusion

This article showed you how to determine if a custom date object or string is today's date by creating a custom function and using some built-in JavaScript magic.

Posted by: Josh Rowe
Created: November 29, 2022

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.