Skip to content

Instantly share code, notes, and snippets.

@jlamberg jlamberg/round_nearest.rb
Last active Mar 30, 2016

Embed
What would you like to do?
Rounding to the given nearest number of seconds in Ruby
class Time
def round_nearest(sec=1)
down = self - (self.to_i % sec)
up = down + sec
difference_down = self - down
difference_up = up - self
if (difference_down < difference_up)
return down
else
return up
end
end
end
# Results using Ruby v2.1.5p273
t = Time.now # => 2016-03-31 00:42:30 +0300
t.round_nearest(60) # => 2016-03-31 00:43:00 +0300
t.round_nearest(300) # => 2016-03-31 00:45:00 +0300
t.round_nearest(600) # => 2016-03-31 00:40:00 +0300
t.round_nearest(660) # => 2016-03-31 00:43:00 +0300
t = Time.new(2015, 12, 29, 11, 46, 0) # => 2015-12-29 11:46:00 +0200
t.round_nearest(60) # => 2015-12-29 11:46:00 +0200
t.round_nearest(300) # => 2015-12-29 11:45:00 +0200
t.round_nearest(600) # => 2015-12-29 11:50:00 +0200
t.round_nearest(660) # => 2015-12-29 11:44:00 +0200
t = Time.utc(2015, 12, 29, 11, 46, 0) # => 2015-12-29 11:46:00 UTC
t.round_nearest(60) # => 2015-12-29 11:46:00 UTC
t.round_nearest(300) # => 2015-12-29 11:45:00 UTC
t.round_nearest(600) # => 2015-12-29 11:50:00 UTC
t.round_nearest(660) # => 2015-12-29 11:45:00 UTC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.