【发布时间】:2017-09-28 06:43:06
【问题描述】:
我有一个这样的时间戳字符串:
2016-01-14T22:43:55Z
2016-01-15T00:04:50Z
2016-01-15T00:44:59+08:30
2016-01-15T01:25:35-05:00
2016-01-15T01:44:31+08:30
2016-01-15T02:22:45-05:00
2016-01-15T02:54:18-05:00
2016-01-15T03:53:26-05:00
2016-01-15T04:32:24-08:00
2016-01-15T06:31:32Z
2016-01-15T07:06:07-05:00
我想对它们进行排序,以便我可以从上面的时间戳中获取起始范围和结束范围。我的做法如下:
List<String> timestamp = new ArrayList<>();
// adding above string timestamp into this list
// now sort it
Collections.sort(timestamp);
这将为我提供上述时间戳列表中的开始和结束范围。这是正确的方法还是有更好的方法?
timestamp.get(0); // start range
timestamp.get(timestamp.size() - 1); // end range
更新
所以我应该做如下的事情:
List<OffsetDateTime> timestamp = new ArrayList<>();
timestamp.add(OffsetDateTime.parse( "2016-01-15T00:44:59+08:30" ));
// add other timestamp string like above and then sort it
Collections.sort(timestamp);
timestamp.get(0); // start range
timestamp.get(timestamp.size() - 1); // end range
【问题讨论】:
-
所有时间戳不在同一个时区。按字母顺序排序不会按时间顺序排序。将它们解析为 Instant,并对 Instant 进行排序(或者只找到最小值和最大值:Collections 类也有方法可以做到这一点)。
-
OffsetDateTime是用于这些字符串的正确类。无需显式转换为Instant,因为OffsetDateTime具有可比性,并且主要按时间线上的点排序,即即时(其次是区域偏移)。请参阅 Basil Bourque 的回答。 @JBNizet(我当然同意按字符串排序不会给出正确的顺序) -
如果你只需要排序后的第一个和最后一个,你可以使用
Collections.min()和Collections.max()而不是Collections.sort()。如果有很多时间戳,这也会更有效率。该技巧也适用于迄今为止发布的答案。 -
如果这些时间戳来自your previous question,为什么不保留那里的
ZonedDateTime对象而不是字符串呢?然后排序,或者只是找到第一个和最后一个,将是一件很容易的事。
标签: java sorting date jodatime