I have an array of dates in ISO8601 format and need to sort them. Does anyone have a suggestion for an algorithm that would work? I don't think they will sort as strings unless I'm much mistaken, so I assume they have to be broken down into their component parts?
Can someone post an algorithm, preferably language agnostic, but VB or C# example would work as long as it just uses strings and integers and no functions that are built-in to the language.
Thanks!
To sort a JavaScript array by ISO 8601 date, we can use the JavaScript array's sort method. We have the arr array that we want to sort by the date value. Then we call arr. sort with a callback that compares the strings to compare the date strings directly by their values lexigraphically.
ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).
Within any specific format, like yyyy-mm-dd or yyyy-Www-d , ISO 8601 is built to sort lexicographically (other than negative years). From the ISO 8601 wikipedia page: Date and time values are organised from the most to the least significant: year, month (or week), day, hour, minute, second, and fraction of second.
The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .
I don't think they will sort as strings unless I'm much mistaken,
You are much mistaken :-). They will sort as strings†. That's one of the major plus points of ISO 8601 over other date formats.
See point 1: http://en.wikipedia.org/wiki/ISO_8601#General_principles
... The lexicographical order of the representation thus corresponds to chronological order...
†as long as you aren't dealing with negative years, an you are using the same timezone and subformat i.e. you don't mix month based and week based (thanks to @paxdiablo and @whiskeysierra for pointing these out)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With