diff --git a/README.markdown b/README.markdown index 629b3ba..f6a0ba4 100644 --- a/README.markdown +++ b/README.markdown @@ -116,6 +116,24 @@ Round to the given nearest number of seconds. Tod::TimeOfDay.new(8,15,31).round(5) # => "08:15:30" Tod::TimeOfDay.new(8,15,34).round(60) # => "08:16:00" Tod::TimeOfDay.new(8,02,29).round(300) # => "08:00:00" + +Floor +---------- + +Round down by given number of seconds. + + Tod::TimeOfDay.new(8,15,31).floor(5) # => "08:15:30" + Tod::TimeOfDay.new(8,15,34).floor(60) # => "08:15:00" + Tod::TimeOfDay.new(8,02,29).floor(300) # => "08:00:00" + +Ceiling +---------- + +Round up by given number of seconds. + + Tod::TimeOfDay.new(8,15,31).ceil(5) # => "08:15:35" + Tod::TimeOfDay.new(8,15,34).ceil(60) # => "08:16:00" + Tod::TimeOfDay.new(8,02,29).ceil(300) # => "08:05:00" Convenience methods for dates and times --------------------------------------- diff --git a/lib/tod/time_of_day.rb b/lib/tod/time_of_day.rb index b99e554..f2fc676 100644 --- a/lib/tod/time_of_day.rb +++ b/lib/tod/time_of_day.rb @@ -70,10 +70,20 @@ def <=>(other) @second_of_day <=> other.second_of_day end + # Rounding down by number of seconds + def floor(sec = 1) + self - (self.to_i % round_sec) + end + + # Rounding up by number of seconds + def ceil(sec = 1) + floor(sec) + sec + end + # Rounding to the given nearest number of seconds def round(round_sec = 1) - down = self - (self.to_i % round_sec) - up = down + round_sec + down = floor(round_sec) + up = ceil(round_sec) difference_down = self - down difference_up = up - self