Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Increment a date using Ruby

This Ruby code converts a string into a date and increments the day, week, month, quarter or year.

def date_add(sdate='', unit='',i=0)

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

date_add("17/03/2008 17:48:00",'months',2)

output: Sat May 17 17:48:00 +0100 2008

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS