简体   繁体   English

如何为给定日期时间的每个日期创建一个哈希/数组次数

[英]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.

相关问题 给定一个DateTime,如何获取特定时区中具有相同日期的时间范围? - Given a DateTime, how do I get the range of times with the same date in a particular time zone? 如何在Ruby中的.each内部创建哈希哈希 - How do I create a hash of hashes inside of a .each in Ruby 如何在Rails中修改日期时间哈希? - How do I modify a datetime hash in Rails? 如何从给定的字符串创建关联数组? - How do I create an array of associations from a given string? 使用 Rails 4.2 和 lograge,如何在每个记录行之前启用日期/时间? - With Rails 4.2 and lograge, how do I enable date/times before each logged line? 在Ruby中,尝试对给定哈希使用.each做 - In Ruby trying to use .each do on a given hash Hash 具有 3 个不同的键,每个键指向一个实例数组。 如何按 id 对 arrays 进行排序? - Hash with 3 different keys each pointing to an array of instances. How do I sort the arrays by id? Rails 5:如何在每次循环中遍历哈希 - Rails 5: How do I loop over a hash with each do 在导轨中,给定Point对象的数组,我如何求和每个玩家的积分值? - In rails, given an array of Point objects, how do I sum the point values for each player? 如何按日期组合数组和哈希 - How to combine array and hash by date
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM