gpt4 book ai didi

ruby-on-rails - 将 Rails DateTime 四舍五入到最接近的 15 分钟间隔

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:51 24 4
gpt4 key购买 nike

我需要将 DateTimeTime 舍入到最接近的 15 分钟间隔。我的想法是将秒和毫秒归零(它们是否存在于 DateTimeTime 中?)甚至纳秒?然后将分钟数除以 15,四舍五入,然后将结果乘以 15 并将其设置为分钟数:

# zero out the seconds
time -= time.sec.seconds
# zero out the milliseconds (does that exist?)
# zero out the nanoseconds (less likely this exists)

minutes_should_be = (time.min / 15.to_f).round * 15
time += (minutes_should_be - time.min).minutes

所以我想我的问题是是否有更好的方法来执行此操作,DateTimeTime 中是否存在毫秒和纳秒?纳秒有一个 nsec 方法,但我认为这是自纪元以来的总纳秒数。

最佳答案

以下应该可以解决问题:

##
# rounds a Time or DateTime to the neares 15 minutes
def round_to_15_minutes(t)
rounded = Time.at((t.to_time.to_i / 900.0).round * 900)
t.is_a?(DateTime) ? rounded.to_datetime : rounded
end

该函数将输入转换为 Time 对象,可以使用 to_i 将其转换为自纪元以来的秒数(这会自动去除纳秒/毫秒)。然后我们除以 15 分钟(900 秒)并四舍五入得到的 float 。这会自动将时间四舍五入到最接近的 15 分钟。现在,我们只需要将结果乘以 15 分钟,然后再次将其转换为(日期)时间。

示例值:

round_to_15_minutes Time.new(2013, 9, 13, 0, 7, 0, "+02:00")
#=> 2013-09-13 00:00:00 +0200
round_to_15_minutes Time.new(2013, 9, 13, 0, 8, 0, "+02:00")
#=> 2013-09-13 00:15:00 +0200
round_to_15_minutes Time.new(2013, 9, 13, 0, 22, 29, "+02:00")
#=> 2013-09-13 00:15:00 +0200
round_to_15_minutes Time.new(2013, 9, 13, 0, 22, 30, "+02:00")
#=> 2013-09-13 00:30:00 +0200
round_to_15_minutes DateTime.now
#=> #<DateTime: 2013-09-13T01:00:00+02:00 ((2456548j,82800s,0n),+7200s,2299161j)>

关于ruby-on-rails - 将 Rails DateTime 四舍五入到最接近的 15 分钟间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18774943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com