Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncating Ruby Time objects efficiently

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?

like image 628
mavam Avatar asked Dec 23 '22 11:12

mavam


1 Answers

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.

like image 166
Greg Campbell Avatar answered Jan 02 '23 06:01

Greg Campbell