JS 中比较两个格式为 HH:MM:SS 的时间字符串
使用字符串比较来比较两个格式为 hh:mm:ss 的时间字符串,例如 if (time1 > time2) {}。 时间字符串的格式为 hh:mm:ss 并且基于 24 小时制,字符串比较的默认行为就足够了。
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 代码,这足以满足我们的目的。
或者,我们可以使用更明确的方法。
比较两个时间字符串:
- 从每个字符串中获取小时、分钟和秒值。
- 使用这些值创建 Date 对象。
- 比较对 Date 对象调用 getTime() 方法的输出。
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');
}
我们创建了 2 个 Date 对象以便能够比较它们的时间戳。
我们传递给 Date() 构造函数的参数是年、月(从零开始的值,其中 January = 0、February = 1 等)、日期、小时、分钟和秒。
getTime 方法返回一个数字,表示从 1970 年 1 月 1 日 00:00:00 到给定日期之间经过的毫秒数。
我们在每个冒号上拆分时间字符串以获得子字符串数组。
const time1 = '07:30:24';
// ?️ ['07', '30', '24']
console.log(time1.split(':'));
我们使用数组解构将子字符串分配给同一行上的变量。
一旦我们从每个日期获得时间戳,我们所要做的就是比较数字。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。