[英]How do I create a hash/array of times for each date given a datetime
I have a column with datetime in a table that has the format: 我在表格中有一个日期时间列,其格式为:
2012-10-30 08:00:00 UTC
How could I create an array or hash that would collect the times by date: 我怎样才能创建一个按日期收集时间的数组或哈希:
2012-10-30
8:00
9:00
13:00
2012-11-02
8:00
9:00
In the end I would like to have web output like this: 最后我想有这样的web输出:
October 30, 2012
8:00 <reserve button>
9:00 <reserve button>
13:00 <reserve button>
November 2, 2012
8:00 <reserve button>
9:00 <reserve button>
I can figure out the html part if I can get the array correctly setup. 如果我可以正确设置数组,我可以找出html部分。
Get all your available timestamps from the table, for example: 从表中获取所有可用的时间戳,例如:
available_times = SomeTable.select(:some_column).order(:some_column).all
Build a Hash by date: 按日期构建哈希:
@result = available_times.inject({}) do |m, timestamp|
date = timestamp.to_date
m[date] ||= []
m[date] << timestamp
m
end
@result will be a Hash by date with available times. @result将按日期和可用时间进行哈希。
You can now do this in your view: 您现在可以在视图中执行此操作:
<% @result.each do |date, timestamps| -%>
<div><%= date.strftime("%B %-d, %Y") %></div>
<% timestamps.each do |timestamp| -%>
<%= timestamp.strftime("%k:%M") %> <input id='<%= timestamp.to_f%>' type='button' value='Reserve Button'/>
<br/>
<% end -%>
<% end -%>
sample = ["2012-10-28 08:30:00 UTC",
"2012-10-28 09:00:00 UTC",
"2012-11-30 09:15:00 UTC",
"2012-11-30 08:00:00 UTC"]
sample.each_with_object(Hash.new{ |h, k| h[k] = [] }) do |d, h|
date = DateTime.parse(d)
h[date.strftime("%B %-d, %Y")] << date.strftime("%k:%M")
end
# => {"October 28, 2012"=>["8:30", "9:00"], "November 30, 2012"=>["9:15", "8:00"]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.