Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- t = Time.new
- rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)
- require 'activesupport/core_ext'
- 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
- end
- t = Time.now # => Thu Jan 15 21:26:36 -0500 2009
- t.round(15.minutes) # => Thu Jan 15 21:30:00 -0500 2009
- t.floor(15.minutes) # => Thu Jan 15 21:15:00 -0500 2009
- t.min - ( t.min % 15)
- time.at_beginning_of_last_fifteen_minutes
- t = Time.new
- rounded_t = t-t.sec-t.min%15*60
- Time.at(t.to_i/(15*60)*(15*60))
- t = Time.new
- truncated_t = Time.at(t.to_i - t.sec - t.min % 15 * 60)
- min / 15 * 15
- 15 => 15
- 16 => 15
- ..
- 29 => 15
- 30 => 30
- (( min + 7.5 ) / 15).to_i * 15
- ( min.to_f / 15 ).round * 15
- # this is an extension of Ryan McGeary's solution, specifically for Rails.
- # Note the use of utc, which is necessary to keep Rails time zone stuff happy.
- # put this in config/initializers/time_extensions
- require 'rubygems'
- require 'active_support'
- module TimeExtensions
- %w[ round floor ceil ].each do |_method|
- define_method _method do |*args|
- seconds = args.first || 60
- Time.at((self.to_f / seconds).send(_method) * seconds).utc
- end
- end
- end
- Time.send :include, TimeExtensions
- class Time
- def round(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
- t = Time.now # => Mon Nov 15 10:18:29 +0200 2010
- t.round(15.minutes) # => Mon Nov 15 10:15:00 +0200 2010
- t.round(20.minutes) # => Mon Nov 15 10:20:00 +0200 2010
- t.round(60.minutes) # => Mon Nov 15 10:00:00 +0200 2010
Add Comment
Please, Sign In to add comment