14

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?

steampowered
  • 11,809
  • 12
  • 78
  • 98
  • 2
    If the format is from big unit --> small unit, and all the strings have the same length for each field (fill in leading 0 if necessary), then there should be no problem. – nhahtdh Dec 05 '12 at 03:01
  • 1
    Relevant links: [Here](http://jsperf.com/date-object-creation/2) shows the ops/sec of using the _Date_ constructor, [here](http://jsperf.com/operator-vs-localecompage/3) is string comparison and [here](http://jsperf.com/inequality-str-vs-int) int comparison. – Paul S. Dec 05 '12 at 03:05
  • According to [wikipedia](https://en.wikipedia.org/wiki/ISO_8601#General_principles), The components of an ISO 8601 date are in lexicographical order, so you should be fine to do the above – Dogoku Feb 24 '17 at 05:29

1 Answers1

13

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.

alex
  • 479,566
  • 201
  • 878
  • 984