在两个 DateTime 之间迭代,以一小时为步长 [英] Iterating between two DateTimes, with a one hour step

查看:44
本文介绍了在两个 DateTime 之间迭代,以一小时为步长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 Ruby 1.9.x/Rails 3.2.x 中以一小时为步长在两个 DateTime 对象之间进行迭代的有效方法.

('2013-01-01'.to_datetime .. '2013-02-01'.to_datetime).step(1.hour) do |date|...结尾

我知道一个问题是 1.hour 只是秒数,但我尝试将其转换为 DateTime 对象并将其用作该步骤也不起作用.

我看了"当心红宝石糖".它在底部附近提到 DateTime 有一个直接的 step 方法.我通过在 DateTime 对象上运行 methods 确认了这一点,但是我在 DateTime 中找不到任何关于 step 的文档,无论是在 Ruby 还是 Rails 的文档中.

解决方案

类似于我在如何从一个范围返回一个天数和小时数数组?",诀窍是使用 to_i 使用自纪元以来的秒数:

('2013-01-01'.to_datetime.to_i .. '2013-02-01'.to_datetime.to_i).step(1.hour) do |date|puts Time.at(date)结尾

请注意,Time.at() 使用您的本地时区进行转换,因此您可能需要使用 Time.at(date).utc 来指定 UTC>

I'm looking for an efficient way, in Ruby 1.9.x/Rails 3.2.x, to iterate between two DateTime objects, with a one-hour step.

('2013-01-01'.to_datetime .. '2013-02-01'.to_datetime).step(1.hour) do |date|
   ...
end

I understand that an issue with this is that 1.hour is just the number of seconds, but my attempts to convert that to a DateTime object and use that as the step doesn't work either.

I looked at "Beware of Ruby Sugar". It mentions, near the bottom, that DateTime has a direct step method. I confirmed this by running methods on a DateTime object, but I cannot find any documentation on step in DateTime, in either Ruby's or Rails' documents.

解决方案

Similar to my answer in "How do I return an array of days and hours from a range?", the trick is to use to_i to work with seconds since the epoch:

('2013-01-01'.to_datetime.to_i .. '2013-02-01'.to_datetime.to_i).step(1.hour) do |date|
  puts Time.at(date)
end

Note that Time.at() converts using your local time zone, so you may want to specify UTC by using Time.at(date).utc

这篇关于在两个 DateTime 之间迭代,以一小时为步长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆