js 中比较两个格式为 hh:mm:ss 的时间字符串-ag捕鱼王app官网

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。

发布时间:2024/03/22 浏览次数:177 分类:javascript

通过 json.parse() 方法访问 javascript 中的 json 对象和数组可以有多种做法。可以使用点(.) 操作或括号对([]) 访问它。

扫一扫阅读全部技术教程

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图