我想从包含各种UTC时间的数组中提取最新的UTC时间。我可以比较UTC中的两个时间戳,如下所示:
#!/usr/bin/ruby
require "time"
a=Time.parse("2013-05-03 16:25:35 UTC")
b=Time.parse("2013-09-07 06:51:24 UTC")
if b < a
puts "latest time is #{a}"
else
puts "latest time is #{b}"
end
输出:
latest time is 2013-09-07 06:51:24 UTC
这样就可以只比较两个时间戳。但是我的数组包含2个以上的UTC时间戳,我需要选择最新的时间戳。以下是Array元素列表:
2013-04-30 12:13:20 UTC
2013-09-07 06:51:24 UTC
2013-05-03 16:25:35 UTC
2013-08-01 07:28:59 UTC
2013-04-09 13:42:36 UTC
2013-09-04 11:40:20 UTC
2013-07-01 06:47:52 UTC
2013-05-03 16:21:54 UTC
我想从阵列选择最新的时间,这将是qazxsw poi
问题:如何根据UTC时间比较所有数组元素?
谢谢。
使用2013-09-07 06:51:24 UTC
:
Enumerable#max
默认情况下,a = [ ... ] # Array of Time instances
latest = a.max
使用max
来比较事物和<=>
存在,所以这可能是最直接的方式。
你的时间戳(几乎)在Time#<=>
和那些明智的比较,所以你可以留下它们作为字符串并将ISO 8601 format应用于一系列字符串。
确切的方法是max
或直接一个Array#sort
Enumerable#max