DEV Community

Samuel Kendrick
Samuel Kendrick

Posted on

Sorting ISO 8601 timestamps

Let's suppose I have a list of timestamps:

timestamps = [
  '2020-06-02T16:47:50Z',
  '2020-05-08T01:25:10Z',
  '2020-05-08T19:51:29Z',
  '2020-06-04T20:23:02Z',
  '2020-05-27T02:23:14Z',
  '2020-05-12T16:32:08Z',
  '2020-05-06T01:58:21Z',
  '2020-05-14T16:11:31Z',
  '2020-05-08T14:25:36Z',
  '2020-05-22T20:48:13Z',
  '2020-05-10T02:43:44Z'
];
Enter fullscreen mode Exit fullscreen mode

Maybe a more "real-world" example would be scenario where you have a list of dictionaries and you want to sort by their created_date attribute. How would you do it?

If we wanted to sort our timestamps we could parse the date string into a date object and then use some compare function to correctly sort the list.

Fortunately, there's a nicer solution! Some date formats, such as ISO 8601 can be sorted merely as strings.

How can this be?

The ISO 8601 format is lexicographically ordered. If you have an ordered set of names: "Carlton" and "Carlyle." When ordered, "Carlton" precedes "Carlyle" because the 5th letter "t" is less than "y".

If you have two timestamps: "2020-05-08T19:51:29Z" and "2020-05-08T01:25:10Z", they differ at the 12th character and, because of the leading 0, the first timestamp comes after the second timestamp.

This is all do say that you can sort your timestamps very easily:

timestamps = [
  '2020-06-02T16:47:50Z',
  '2020-05-08T01:25:10Z',
  '2020-05-08T19:51:29Z',
  '2020-06-04T20:23:02Z',
  '2020-05-27T02:23:14Z',
  '2020-05-12T16:32:08Z',
  '2020-05-06T01:58:21Z',
  '2020-05-14T16:11:31Z',
  '2020-05-08T14:25:36Z',
  '2020-05-22T20:48:13Z',
  '2020-05-10T02:43:44Z'
];
timestamps.sort() # Yay!
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
alerinaldi profile image
Alessandro Rinaldi

That's not always the case, unfortunately. That's not true if you're comparing across different timezones, or even in the same timezone across Daylight Saving Time changes.

Take those two examples:

  • 2022-10-30T02:58:00+02:00
  • 2022-10-30T02:02:00+01:00

The first one is the previous one, it's 4 minutes before the second one. However, sorting alphabetically puts the second one first.