Last updated: Mar 6, 2024
Reading time·2 min
Use string comparison to compare two time strings, that are formatted as
hh:mm:ss
.
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.
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.
This is a two-step process:
Date
object.getTime()
method on the Date
objects.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
.
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.
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 String.split() the time strings on each colon to get an array of substrings.
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.
You can learn more about the related topics by checking out the following tutorials: