找到两个日期范围之间的日期范围

时间:2013-01-27 08:31:53

标签: ruby-on-rails ruby

我想知道Ruby是否有一种简单的方法来查找两个日期范围之间的所有日期范围。我有两个日期数组:一个数组中有January 01, 08:00January 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

1 个答案:

答案 0 :(得分:2)

这是一种方法:

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) } }