ruby-on-rails – 将Rails DateTime四舍五入到最近的15分钟间隔
发布时间:2020-12-17 03:48:18 所属栏目:百科 来源:网络整理
导读:我需要将DateTime和时间四舍五入到最近的15分钟间隔.我的想法是将秒和毫秒(那些存在于DateTime或Time?中)归零,甚至可能是纳秒?然后将分钟数除以15,然后将结果乘以15并将其设置为分钟: # zero out the secondstime -= time.sec.seconds# zero out the mill
我需要将DateTime和时间四舍五入到最近的15分钟间隔.我的想法是将秒和毫秒(那些存在于DateTime或Time?中)归零,甚至可能是纳秒?然后将分钟数除以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 所以我想我的问题是,如果有更好的方法来做到这一点,并且在DateTime或Time中是否存在毫秒和纳秒?有纳秒的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秒)除以得到的浮子.这会自动将时间四舍五入到最近的15分钟.现在,我们只需将结果乘以15分钟,然后再将其转换为(日期)时间. 示例值: round_to_15_minutes Time.new(2013,9,13,7,"+02:00") #=> 2013-09-13 00:00:00 +0200 round_to_15_minutes Time.new(2013,8,"+02:00") #=> 2013-09-13 00:15:00 +0200 round_to_15_minutes Time.new(2013,22,29,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)> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |