How to tell if two dates are in the same day or in the same hour?
JavascriptTypescriptJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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()
.
Solution 2 - Javascript
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