I am trying to come up with an efficient method for truncating Ruby Time objects according to a given resolution.
class Time
def truncate resolution
t = to_a
case resolution
when :min
t[0] = 0
when :hour
t[0] = t[1] = 0
when :day
t[0] = t[1] = 0
t[2] = 1
when :month
t[0] = t[1] = 0
t[2] = t[3] = 1
when :week
t[0] = t[1] = 0
t[2] = 1
t[3] -= t[6] - 1
when :year
t[0] = t[1] = 0
t[2] = t[3] = t[4] = 1
end
Time.local *t
end
end
Does anyone know a faster version that achieves the same task?
This has already been implemented for you in Rails' ActiveSupport library's Time extensions. See the change
method, as well as the various at_beginning_of_*
methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With