如何在 Ruby 中将时间四舍五入到最接近的 15 分钟? [英] How to round a time down to the nearest 15 minutes in Ruby?
问题描述
是否有一种简单的方法可以将时间四舍五入到最接近的 15 分钟?
Is there an easy way to round a Time down to the nearest 15 minutes?
这就是我目前正在做的事情.有没有更简单的方法?
This is what I'm currently doing. Is there an easier way to do it?
t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)
推荐答案
您说的是向下舍入",所以我不确定您实际上是在寻找圆形还是地板,但这是同时执行这两种操作的代码.我认为,如果您将 round_off
和 floor
方法添加到 Time 类中,这样的内容会非常好读.额外的好处是您可以更轻松地按任何时间分区舍入.
You said "round down", so I'm not sure if you're actually looking for the round or the floor, but here's the code to do both. I think something like this reads really well if you add round_off
and floor
methods to the Time class. The added benefit is that you can more easily round by any time partition.
require 'active_support/core_ext/numeric' # from gem 'activesupport'
class Time
# Time#round already exists with different meaning in Ruby 1.9
def round_off(seconds = 60)
Time.at((self.to_f / seconds).round * seconds).utc
end
def floor(seconds = 60)
Time.at((self.to_f / seconds).floor * seconds).utc
end
end
t = Time.now # => Thu Jan 15 21:26:36 -0500 2009
t.round_off(15.minutes) # => Thu Jan 15 21:30:00 -0500 2009
t.floor(15.minutes) # => Thu Jan 15 21:15:00 -0500 2009
注意: ActiveSupport 仅对于漂亮的 15.minutes
参数是必需的.如果您不想要这种依赖关系,请改用 15 * 60
.
Note: ActiveSupport was only necessary for the pretty 15.minutes
argument. If you don't want that dependency, use 15 * 60
instead.
这篇关于如何在 Ruby 中将时间四舍五入到最接近的 15 分钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!