2015-08-28 58 views
-1

之间每隔一小时的阵列我想有输出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(',')}}}}" 
+0

是'{{2015 - {07- 19- {21,22,23},{20- 00,01,02,03,04 ,05,06,07,08,09,10}}}}'应该是一个字符串?如果是这样,你需要用引号括起来。 –

回答

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