迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 >

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

作者:迹忆客 最近更新:2022/12/22 浏览次数:

使用字符串比较来比较两个格式为 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');
}

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

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

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

比较两个时间字符串:

  1. 从每个字符串中获取小时、分钟和秒值。
  2. 使用这些值创建 Date 对象。
  3. 比较对 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(':'));

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

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

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 中加载 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。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便