Compare ISO 8601 date strings in javascript

*爱你&永不变心* 提交于 2021-01-21 07:03:10

问题


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.

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?


回答1:


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). 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.



来源:https://stackoverflow.com/questions/13715561/compare-iso-8601-date-strings-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!