简体   繁体   English

在javascript中比较ISO 8601日期字符串

[英]Compare ISO 8601 date strings in javascript

I want to compare ISO 8601 dates in javascript as strings instead of making Date objects for each string and comparing objects. 我想将javascript中的ISO 8601日期作为字符串进行比较,而不是为每个字符串创建Date对象并比较对象。

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. 我这样做的原因是我认为字符串比较应该比为每个日期字符串制作对象和比较对象更快。

These comparisons seem to work as expected in some browsers. 这些比较似乎在某些浏览器中按预期工作。 Can I expect this sort of alphabetical lexicographic string comparison to work in all browsers? 我可以期望这种 按字母 顺序 排列的 词典字符串比较适用于所有浏览器吗? Is this method of date comparison actually faster than using Date objects? 这种日期比较方法实际上比使用Date对象更快吗?

Using that comparison operator will look at the strings values lexicographically , which means the dictionary order . 使用比较操作将着眼于字符串值字典顺序 ,这意味着字典顺序

In ASCII, the decimal digits are sequentially stored smallest ( 0 , 0x30 ) to largest ( 9 , 0x39 ). 在ASCII,十进制数字被顺序地存储最小( 00x30 )到最大( 90x39 )。 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. 如果它们始终采用这种格式,最大值(年份)到最小值(日期)并且总是0填充到最大可能值,那么这些比较就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM