Compare two Time strings formatted as HH:MM:SS in JS

avatar

Borislav Hadzhiev

Last updated: Jan 23, 2022

banner

Photo from Unsplash

Compare two Time strings formatted as HH:MM:SS in JS #

Use string comparison to compare two time strings, that are formatted as hh:mm:ss, e.g. if (time1 > time2) {}. The time strings are formatted as hh:mm:ss and are based on a 24 hour clock, the default behavior for string comparison is sufficient.

index.js
const time1 = '07:30:24'; const time2 = '10:45:33'; if (time1 > time2) { console.log('time1 is greater than time2'); } else if (time2 > time1) { // ✅ this runs console.log('time2 is greater than time1'); } else { console.log('time1 is equal to time2'); }

If the time strings are consistently formatted as hh:mm:ss and are based on a 24 hour clock, the default behavior for comparing strings is to compare their ASCII codes, which is sufficient for our purposes.

Alternatively, you can use a more explicit approach.

To compare two time strings:

  1. Get the hour, minute and seconds value from each string.
  2. Use the values to create a Date object.
  3. Compare the output from calling the getTime() method on the Date objects.
index.js
const time1 = '07:30:24'; const time2 = '10:45:33'; const [hours1, minutes1, seconds1] = time1.split(':'); const [hours2, minutes2, seconds2] = time2.split(':'); const date1 = new Date(2022, 0, 1, +hours1, +minutes1, +seconds1); const date2 = new Date(2022, 0, 1, +hours2, +minutes2, +seconds2); if (date1.getTime() > date2.getTime()) { console.log('time1 is greater than time2'); } else if (date2.getTime() > date1.getTime()) { // ✅ this runs console.log('time2 is greater than time1'); } else { console.log('time1 is equal to time2'); }

We created 2 Date objects to be able to compare their timestamps.

The parameters we passed to the Date() constructor are the year, month (zero-based value, where January = 0, February = 1, etc), day of the month, hours, minutes and seconds.

The date we passed to the Date() constructor does not matter, as long as it's the same year, month and day of the month for both dates.

The getTime method returns a number that represents the milliseconds elapsed between the 1st of January, 1970 00:00:00 and the given date.

So if the time stored in the time2 variable is greater than the one stored in time1, its timestamp will also be greater, as more time has passed since the Unix Epoch.

We split the time strings on each colon to get an array of substrings.

index.js
const time1 = '07:30:24'; // 👇️ ['07', '30', '24'] console.log(time1.split(':'));

We used array destructuring to assign the substrings to variables on the same line.

Once we get the timestamp from each date, all we have to do is compare the numbers.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.