Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

sorting - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...