Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a time down to the nearest 15 minutes in Ruby?

Tags:

ruby

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) 
like image 692
readonly Avatar asked Jan 16 '09 01:01

readonly


People also ask

How do I round to the nearest minute?

You also can use this formula =MROUND(A2,15/60/24) to round time to nearest minute.

How do you round date and time?

Rounding Up Date ObjectsRound up to the next closest rounding unit boundary. For example, if the rounding unit is month then next closest boundary of 2000-01-01 is 2000-02-01 00:00:00 .


2 Answers

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 

Note: ActiveSupport was only necessary for the pretty 15.minutes argument. If you don't want that dependency, use 15 * 60 instead.

like image 70
Ryan McGeary Avatar answered Sep 18 '22 02:09

Ryan McGeary


I am not very familiar with the syntax of ruby but you can round down to the nearest 15 minutes using modulo. (i.e. x - (x modulo 15)). I would guess the syntax would be something like

t.min - ( t.min % 15) 

This will make your set of possible values 0, 15, 30, and 45. Assuming 0 <= t.min <= 59.

like image 38
cmsjr Avatar answered Sep 19 '22 02:09

cmsjr