The JavaScript Date object compare dates with time including, so, if you compare: time1.getTime() === time2.getTime()
, they'll be "false" if at least one millisecond is different.
What we need is to have a nice way to compare by Hour, Day, Week, Month, Year? Some of them are easy, like year: time1.getYear() === time2.getYear()
but with day, month, hour it is more complex, as it requires multiple validations or divisions.
Is there any nice module or optimized code for doing those comparisons?
Comparing Two Dates in JavaScript Note: Equality operators ( == and === ) don't work with Date objects, so we don't explicitly check if they're the same. Another way to compare two dates is by using the built-in getTime() method. The getTime() method returns the number of milliseconds elapsed since the Unix epoch.
Call the getTime() method on each date to get a timestamp. Compare the timestamp of the dates. If a date's timestamp is greater than another's, then that date comes after.
To check if a date is before another date, compare the Date objects, e.g. date1 < date2 . If the comparison returns true , then the first date is before the second, otherwise the first date is equal to or comes after the second.
To check if a date is yesterday:Subtract 1 day from the current date to get yesterday's date.
The Date prototype has APIs that allow you to check the year, month, and day-of-month, which seems simple and effective.
You'll want to decide whether your application needs the dates to be the same from the point of view of the locale where your code runs, or if the comparison should be based on UTC values.
function sameDay(d1, d2) { return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate(); }
There are corresponding UTC getters getUTCFullYear()
, getUTCMonth()
, and getUTCDate()
.
var isSameDay = (dateToCheck.getDate() === actualDate.getDate() && dateToCheck.getMonth() === actualDate.getMonth() && dateToCheck.getFullYear() === actualDate.getFullYear())
That will ensure the dates are in the same day.
Read more about Javascript
Date
to string
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