Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 402
steampowered Avatar asked Dec 05 '12 02:12

steampowered


People also ask

Can you compare ISO strings?

ISO date strings are nice because you can compare them alphabeticall y and you get a result that makes sense conceptually. You can't compare just any date string. For instance, "13-Dec-2020" < "20-Apr-2020" alphabetically but not conceptually.

How do I compare ISO dates?

To compare two dates, you can use either toString() or valueOf() . The toString() method converts the date into an ISO date string, and the valueOf() method converts the date into milliseconds since the epoch.

How do you compare dates in JavaScript?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.

How do I compare date strings?

To compare two date strings:Pass the strings to the Date() constructor to create 2 Date objects. Compare the output from calling the getTime() method on the dates.


1 Answers

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.

like image 174
alex Avatar answered Sep 28 '22 03:09

alex