Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort ISO 8601 dates forward or backwards

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!

like image 985
alphablender Avatar asked Mar 06 '12 01:03

alphablender


People also ask

Can I sort by ISO date string?

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.

How do I format a date in ISO 8601?

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

Is ISO date sortable?

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.

Is ISO 8601 always UTC?

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 .


1 Answers

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)

like image 131
rjmunro Avatar answered Oct 31 '22 08:10

rjmunro