如何从时间戳列表中获取开始和结束范围? [英] How to get start and end range from list of timestamps?
问题描述
我有一个这样的时间戳字符串:
I have a timestamp string like this:
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
我想对它们进行排序,以便我可以获得起始范围和从上面的时间戳结束范围。我的行为如下:
I want to sort them so that I can get what is starting range and ending range from above timestamp. I am doing like below:
List<String> timestamp = new ArrayList<>();
// adding above string timestamp into this list
// now sort it
Collections.sort(timestamp);
这将从上面的时间戳列表中给出开始和结束范围。这是正确的方法还是有更好的方法?
This will give me start and end range from the above list of timestamp. Is this the right way to do it or there is any better way?
timestamp.get(0); // start range
timestamp.get(timestamp.size() - 1); // end range
更新
所以我应该做类似下面的事情:
So I should do something like below:
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
推荐答案
OffsetDateTime
解析那些 ISO 8601 将字符串转换为 java.time.OffsetDateTime
对象。
OffsetDateTime
Parse those ISO 8601 strings into java.time.OffsetDateTime
objects.
OffsetDateTime.parse( "2016-01-15T00:44:59+08:30" )
将这些日期时间对象添加到集合
并进行排序。您可能需要 List
,例如 ArrayList
或 SortedSet
。
Add those date-time objects to a Collection
and sort. You probably want a List
such as ArrayList
or a SortedSet
.
java.time类实现 compareTo
方法,以 可比较
。所以这些对象知道如何排序。
The java.time classes implement the compareTo
method, to fulfill their contract as a Comparable
. So these objects know how to sort.
像这样:
List<OffsetDateTime> odts = new ArrayList<>();
OffsetDateTime odt = OffsetDateTime.parse( "2016-01-15T00:44:59+08:30" ) ;
odts.add( odt );
… // Parse remaining ISO 8601 strings, adding each new OffsetDateTime object to collection.
Collections.sort( odts );
这篇关于如何从时间戳列表中获取开始和结束范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!