Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if two dates are in the same day or in the same hour? [duplicate]

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?

like image 817
reza Avatar asked May 08 '17 18:05

reza


People also ask

How do you compare two dates that are equal?

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.

How do you know if two dates are equal in typescript?

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.

How do you check if a date is before another date?

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.

How do you know if a date was yesterday?

To check if a date is yesterday:Subtract 1 day from the current date to get yesterday's date.


2 Answers

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

like image 65
Pointy Avatar answered Sep 28 '22 01:09

Pointy


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

like image 44
Daniel Taub Avatar answered Sep 28 '22 01:09

Daniel Taub