stew(@)rtmatheson.com

Thoughts on Rails, Ruby, and Javascript

Rounding Time to the Closest Hour in Ruby

Ahhh… its one of the moments in life that make you so happy your a ruby developer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Time
  def round(seconds = 60)
    Time.at((self.to_f / seconds).round * seconds)
  end

  def floor(seconds = 60)
    Time.at((self.to_f / seconds).floor * seconds)
  end

  def round_to_closest_hour
    if self.min > 30
      self.round(1.hour)
    else
      self.floor(1.hour)
    end
  end
end

Source: http://stackoverflow.com/questions/449271/how-to-round-a-time-down-to-the-nearest-15-minutes-in-ruby