在 JS 中比较两个格式为 HH:MM:SS 的时间字符串

在 JS 中比较两个格式为 HH:MM:SS 的时间字符串

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

使用字符串比较来比较两个时间字符串,格式为
hh:mm:ss,例如if (time1 > time2) {}时间字符串的格式为
hh:mm:ss24 小时制,字符串比较的默认行为就足够了。

索引.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'); }

如果时间字符串的格式一致hh:mm:ss并基于 24 小时制,则比较字符串的默认行为是比较它们的 ASCII 代码,这足以满足我们的目的。

或者,您可以使用更明确的方法。

比较两个时间字符串:

  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.

因此,如果存储在time2变量中的时间大于存储在中time1的时间,则其时间戳也将更大,因为自 Unix 纪元以来已经过去了更多时间。

我们
在每个冒号上
拆分
时间字符串以获得子字符串数组。

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

我们使用数组解构将子字符串分配给同一行上的变量。

一旦我们从每个日期获得时间戳,我们所要做的就是比较数字。