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.
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.