在两个日期时间之间返回每小时的数组

时间:2015-08-28 23:55:27

标签: ruby

我希望输出date_glob看起来像:

{2015-{07-{19-{21,22,23},20-{00,01,02,03,04,05,06,07,08,09,10}}}}

感谢您的帮助。以下是我的剧本。

require 'date'

date_glob = ""; y = 0; m = 0;
(DateTime.new(2015,7,19,21,0,0)..DateTime.new(2015,7,20,10,0,0)).each do |d|
  if d.year != y
    date_glob = "#{date_glob.chomp(',')}}}," if y != 0
    date_glob+= "#{d.year}-{"
    m = 0
  end
  if d.month != m
    date_glob = "#{date_glob.chomp(',')}}," if m != 0
    date_glob+= sprintf("%02d-{",d.month)
  end
  date_glob+= sprintf("%02d-",d.day)
  date_glob+= sprintf("%02d,",d.hour)
  y = d.year
  m = d.month
end
date_glob = "{#{date_glob.chomp(',')}}}}"

1 个答案:

答案 0 :(得分:2)

一个简单的解决方案可能是:

date = DateTime.new(2015,7,19,21,0,0)
end_date = DateTime.new(2015,7,20,10,0,0)
hash = {}
while date <= end_date
  hash[date.year] ||= {}
  hash[date.year][date.month] ||= {}
  hash[date.year][date.month][date.day] ||= []
  hash[date.year][date.month][date.day] << date.hour
  date = date.in(1.hour)
end

hash
=> {2015=>{7=>{19=>[21, 22, 23], 20=>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}}} 

hash.to_s.gsub("=>",'-').gsub("[","{").gsub("]","}").gsub(/\s+/,'')
=> "{2015-{7-{19-{21,22,23},20-{0,1,2,3,4,5,6,7,8,9,10}}}}"