js – how to compare (is before / after) two datetimes in terms of time of the day (ignoring date)

I have the dayjs library in the project but cannot find a good way of comparing just the time of the day between two datetime objects.

The closest I got was doing: dayjs(dateTime1).isAfter(dateTime2, ‘hour’) but that does not take into account minutes, leading to incorrect edge cases.

Thanks

I probably could just regex the time part and then do some comparison but I’m hoping I won’t need to do any conversion. I don’t need to use dayjs. Can be pure js.

  • 1

    Make a clone of one of the dates, set its day/month/year to that of the other date, and then compare.

    – 

If you only want minute-resolution, the simple way is to get minutes-since-midnight by multiplying the hours value by 60 and adding the minutes value: hours * 60 + minutes. Then you can compare the numbers.

Here’s a simple example using JavaScript’s built-in Date type (though perhaps these days I should be using Temporal):

function compareTime(dt1, dt2) {
    const mins1 = dt1.getHours() * 60 + dt1.getMinutes();
    const mins2 = dt2.getHours() * 60 + dt2.getMinutes();
    return mins2 - mins1;
}

// First date's time-of-day is before second date's time-of-day
console.log(compareTime(
    new Date("2023-10-07T10:30"),
    new Date("2023-09-17T11:30"),
));

// Times-of-day are the same
console.log(compareTime(
    new Date("2023-10-07T13:30"),
    new Date("2023-09-17T13:30"),
));

// First date's time-of-day is before second date's time-of-day
console.log(compareTime(
    new Date("2023-10-07T13:30"),
    new Date("2023-09-17T11:30"),
));

For seconds-resolution, it’s ((hours * 60) + minutes) * 60 + seconds.

Leave a Comment