计算日期

先写一个方法。

 

    def date_add(sdate = '', unit = '', i = 0)
      sdate[/(\d+)\/(\d+)\/(\d+)\s(\d+):(\d+):(\d+)/]
      iyear, imonth, iday, ihour, imin, isec = $3.to_i, $2.to_i, $1.to_i, $4.to_i, $5.to_i, $6.to_i
      case  unit
      when 'days'
        time = Time.local(iyear, imonth, iday, ihour, imin, isec)
        time += (60 * 60 * 24 * i)
      when 'weeks'
        time = Time.local(iyear, imonth, iday, ihour, imin, isec)
        time += (60 * 60 * 24 * 7 * i)
      when 'months'
        imonth += i
        if imonth <= 12
          time = Time.local(iyear, imonth, iday, ihour, imin, isec)
        else
          time = Time.local(iyear + imonth / 12, imonth - 12 * (imonth / 12), iday, ihour, imin, isec)
        end
      when 'quarters'
        imonth += 3 * i
        if imonth <= 12 then
          time = Time.local(iyear, imonth, iday, ihour, imin, isec)
        else
          time = Time.local(iyear + imonth / 12, imonth - 12 * (imonth / 12), iday, ihour, imin, isec)
        end
      when 'years'
        time = Time.local(iyear + i, imonth, iday, ihour, imin, isec)
      else
        raise 'not a valid date unit'
      end
      time
    end

 

具体示例:

 

 date_add("20/01/2009 17:48:00", 'months', 50)

 

你可能感兴趣的:(日期)