Last active
March 30, 2016 22:10
Star
You must be signed in to star a gist
Rounding to the given nearest number of seconds in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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