我想知道 Ruby 是否有一种简单的方法来查找两个日期范围之间的所有日期范围。我有两个日期数组:一个数组,January 01, 08:00
另一个数组。我想返回一个数组,如:January 01, 12:00
January 01, 09:00 to January 01, 10:00
January 1, 08:00 to January 1, 09:00
和:
January 1, 10:00 to January 1, 12:00
我想知道 Ruby 是否有一种简单的方法来查找两个日期范围之间的所有日期范围。我有两个日期数组:一个数组,January 01, 08:00
另一个数组。我想返回一个数组,如:January 01, 12:00
January 01, 09:00 to January 01, 10:00
January 1, 08:00 to January 1, 09:00
和:
January 1, 10:00 to January 1, 12:00
这是一种方法:
date_array_1, date_array_2 = [
'January 01, 08:00', 'January 01, 12:00',
'January 01, 09:00', 'January 01, 10:00'
].map{ |s| DateTime.parse(s) }.each_slice(2).to_a
这设置了两个日期数组。
require 'date'
def date_ranges(ary1, ary2)
[
ary1,
ary2
].flatten.sort.each_slice(2).map{ |s| s.first .. s.last }
end
puts date_ranges(date_array_1, date_array_2)
哪个输出:
2013-01-01T08:00:00+00:00..2013-01-01T09:00:00+00:00
2013-01-01T10:00:00+00:00..2013-01-01T12:00:00+00:00
如果我想让 date_array_2 成为日期数组?这简单吗?像 date_array_1 = ['January 01, 08:00', 'January 01, 13:00'] date_array_2 = [['January 01, 09:00', 'January 01, 10:00'], ['January 01, 11:00', '1 月 1 日 12:00']]
两个日期数组如下所示:
date_array_1 = ['January 01, 08:00', 'January 01, 12:00']
date_array_2 = ['January 01, 09:00', 'January 01, 10:00']
将它们强制转换为 DateTime 对象:
[ date_array_1, date_array_2 ].map{ |a| a.map!{ |d| DateTime.parse(d) } }