algorithmsortingdatedate-sorting

Date string format that sorted lexicographically ascending is chronologically descending?


Encoding calendar dates as strings in the YYYY-MM-DD format (with or without separators, e.g. 2014-04-21, 2014.04.21 or 20140421) has the following properties:

Note that for this to work, each component of the date (year, month and day) must always use the same number of characters, with leading zeroes if the number is too small. This means that YYYY can only represent years up to 9999. If we want to represent 5-digit years too, then the date in my example above becomes 02014-04-21.

Question:

Is there a way to encode calendar dates as strings, such that sorting the strings lexicographically ascending puts them in reverse chronological order?

Ideally, it would be easy for a human to convert between the calendar date and the format you suggest, but even if you don't manage this (my solution below doesn't) I still want to know your solution.

If it helps, you may require this restriction:

All I could come up with is this:

The main problem with my solution is that it's not obvious to a human that 86-09-11 represents April 21, 2014.

Notes:


Solution

  • You could use 9's complement -- write down the ISO date and then replace each digit by 9 minus that digit. At least I can apply in my head the encode/decode function (they're the same). I don't understand, however, why you don't just keep some redundant information around, turning 2006-01-02 into HJJD-JI-JH-2006-01-02, deriving 2006-01-02 -> 7993-98-97 -> HJJD-JI-JH by replacing 0 -> A, 1 -> B, 2 -> C, 3 -> D, 4 -> E, 5 -> F, 6 -> G, 7 -> H, 8 -> I, 9 -> J.