将ISO 8601日期向前或向后排序 [英] Sort ISO 8601 dates forward or backwards

查看:125
本文介绍了将ISO 8601日期向前或向后排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ISO8601格式的日期数组,需要对其进行排序.有人对可行的算法有建议吗?我认为除非我很误解,否则它们不会按字符串排序,因此我认为必须将它们分解为它们的组成部分?

有人可以发布一种算法,最好是与语言无关的算法,但是VB或C#示例可以使用,只要它仅使用字符串和整数,并且不使用语言内置的函数即可.

谢谢!

解决方案

这取决于您是否要混合格式.

在任何特定格式(例如yyyy-mm-ddyyyy-Www-d)中,ISO 8601都是按字典顺序(负数年除外)进行构建的.

ISO 8601维基百科页面中:

日期和时间值的排列顺序从最高到最低:年,月(或周),日,时,分,秒和秒的一部分.因此,表述的字典顺序对应于时间顺序,但涉及负年的日期表述除外.这样就可以通过文件系统对日期进行自然排序.

这意味着字符串排序应该可以.

仅当您 mix 格式不起作用时才可以.在这种情况下,您需要先将其转换为特定格式,然后再进行比较.这样,我的意思是像在比较之前将所有格式都转换为yyyy-mm-dd,然后在需要时将其转换回

2010-03-01
2010-W01-1

.

例如,如果您有输入数据:

2010-03-01
2010-W01-1

您可以先将它们全部更改为:

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

(以特定格式为实际数据添加前缀)然后进行排序.排序后,您可以返回并剥离所有内容,直到每个元素的第一个:字符,这将恢复原始格式.

不一定是最有效的方法,但是如果您想保留原始形式,则需要执行 这样的操作.如果这不是问题,只需将它们转换为特定形式一次,然后像这样保留它们即可.

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!

解决方案

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.

这篇关于将ISO 8601日期向前或向后排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆