本文介绍了比较 javascript 中的 ISO 8601 日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 javascript 中的 ISO 8601 日期作为字符串进行比较,而不是为每个字符串制作 Date 对象并比较对象.

I want to compare ISO 8601 dates in javascript as strings instead of making Date objects for each string and comparing objects.

var date_array = ['2012-10-01','2012-11-27','2012-12-23'];
console.log(date_array[0] < date_array[1])  // gives true
console.log(date_array[1] > date_array[2])  // gives false

我这样做的原因是我相信字符串比较应该比为每个日期字符串创建对象并比较对象更快.

My reason for doing this is I believe string comparisons should be faster than making objects for each date string and comparing objects.

这些比较似乎在某些浏览器中按预期工作.我可以期望这种 lexicographic 字符串比较适用于所有浏览器吗?这种日期比较的方法实际上比使用Date对象更快吗?

These comparisons seem to work as expected in some browsers. Can I expect this sort of lexicographic string comparison to work in all browsers? Is this method of date comparison actually faster than using Date objects?

推荐答案

使用该比较运算符将查看字符串值 字典序,表示字典顺序.

Using that comparison operator will look at the strings values lexicographically, which means the dictionary order.

在 ASCII 中,十进制数字按最小 (0, 0x30) 到最大 (9, 0x39) 顺序存储代码>).如果它们始终采用这种格式,从最大值(年)到最小值(日)并且总是 0 填充到可能的最大值,那么这些比较就可以了.

In ASCII, the decimal digits are sequentially stored smallest (0, 0x30) to largest (9, 0x39). If they're consistently in this format, largest value (year) to smallest (day) and always 0 padded to the largest possible value, then these comparisons will be fine.

这篇关于比较 javascript 中的 ISO 8601 日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 05:08