Sort ISO 8601 dates forward or backwards

后端 未结 2 1993
情话喂你
情话喂你 2020-12-10 13:43

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 un

相关标签:
2条回答
  • 2020-12-10 14:00

    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)

    0 讨论(0)
  • 2020-12-10 14:12

    It depends on whether or not you're mixing formats.

    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 lexicographical order of the representation thus corresponds to chronological order, except for date representations involving negative years. This allows dates to be naturally sorted by, for example, file systems.

    That means that string sorting should work okay.

    It's only if you mix formats will that not work. If that's the case, you'll need to convert to a specific format before comparing. By that, I mean something like converting all formats into yyyy-mm-dd before comparison and then back afterwards if desired.

    For example, if you have the input data:

    2010-03-01
    2010-W01-1
    

    you could first change them all to:

    2010-03-01:2010-03-01
    2010-01-04:2010-W01-1
    

    (prefixing the actual data with a specific form) then sort that. Once sorted, you then go back and strip off everything up to the first : character in each element, which will recover the original form.

    Not necessarily the most efficient way but you'll need to do something like that if you want to preserve the original form. If that's not an issue, simply convert them to the specific form once and leave them like that.

    0 讨论(0)
提交回复
热议问题