有效地截断Ruby Time对象

mav*_*vam 3 ruby time truncate date

我试图提出一种根据给定的分辨率截断Ruby Time对象的有效方法.

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
Run Code Online (Sandbox Code Playgroud)

有谁知道更快的版本,实现相同的任务?

Gre*_*ell 6

这已经在Rails的ActiveSupport库的时间扩展中为您实现.请参阅change方法以及各种at_beginning_of_*方法.