Skip to content

Instantly share code, notes, and snippets.

@jlamberg
Last active March 30, 2016 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlamberg/576318a1d740924263d5ce5834e35cf4 to your computer and use it in GitHub Desktop.
Save jlamberg/576318a1d740924263d5ce5834e35cf4 to your computer and use it in GitHub Desktop.
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