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 等)、日期、小时、分钟和秒。
我们传递给 Date() 构造函数的日期并不重要,只要两个日期的年月日相同即可。
getTime
方法返回一个数字,表示从 1970 年 1 月 1 日 00:00:00 到给定日期之间经过的毫秒数。
因此
,如果存储在 time2 变量中的时间大于存储在 time1 中的时间,则其时间戳也将更大,因为自 Unix 纪元以来已经过去了更多时间。
我们在每个冒号上拆分时间字符串以获得子字符串数组。
const time1 = '07:30:24';
// 👇️ ['07', '30', '24']
console.log(time1.split(':'));
我们使用数组解构将子字符串分配给同一行上的变量。
一旦我们从每个日期获得时间戳,我们所要做的就是比较数字。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
将 Pandas DataFrame 转换为 JSON
发布时间:2024/04/21 浏览次数:153 分类:Python
-
本教程演示了如何将 Pandas DataFrame 转换为 JSON 字符串。
在 Pandas 中加载 JSON 文件
发布时间:2024/04/21 浏览次数:105 分类:Python
-
本教程介绍了我们如何使用 pandas.read_json()方法将一个 JSON 文件加载到 Pandas DataFrame 中。
将 JSON 转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:135 分类:Python
-
本教程演示了如何使用 json_normalize()和 read_json()将 JSON 字符串转换为 Pandas DataFrame。
从 JavaScript 中的 JSON 对象获取值
发布时间:2024/03/22 浏览次数:177 分类:JavaScript
-
通过 JSON.parse() 方法访问 JavaScript 中的 JSON 对象和数组可以有多种做法。可以使用点(.) 操作或括号对([]) 访问它。