I have a date object in JavaScript and I want to figure out if that date is today. What is the fastest way of doing this?
My concern was around comparing date object as one might have a different time than another but any time on today's date should return true
.
To check if a date is today's date:Use the Date() constructor to get today's date. Use the toDateString() method to compare the two dates. If the method returns 2 equal strings, the date is today's date.
now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.
Use new Date() to generate a new Date object containing the current date and time. This will give you today's date in the format of mm/dd/yyyy.
You could use toDateString
:
var d = new Date() var bool = (d.toDateString() === otherDate.toDateString());
The answers based on toDateString()
will work I think, but I personally would avoid them since they basically ask the wrong question.
Here is a simple implementation:
function areSameDate(d1, d2) { return d1.getFullYear() == d2.getFullYear() && d1.getMonth() == d2.getMonth() && d1.getDate() == d2.getDate(); }
MDN has a decent overview of the JS Date object API if this isn't quite what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With