Increment a date using Ruby
1 2 def date_add(sdate='', unit='',i=0) 3 4 sdate[/(\d+)\/(\d+)\/(\d+)\s(\d+):(\d+):(\d+)/] 5 iyear = $3.to_i; imonth = $2.to_i; iday = $1.to_i; ihour = $4.to_i; imin = $5.to_i; isec = $6.to_i 6 7 case unit 8 when 'days' 9 t1 = Time.local(iyear,imonth,iday,ihour,imin,isec) 10 t1 += (60 * 60 * 24 * i) 11 when 'weeks' 12 t1 = Time.local(iyear,imonth,iday,ihour,imin,isec) 13 t1 += (60 * 60 * 24 * 7 * i) 14 when 'months' 15 imonth += i 16 if imonth < 12 then 17 t1 = Time.local(iyear,imonth+i,iday,ihour,imin,isec) 18 else 19 t1 = Time.local(iyear+=1,imonth -12,iday,ihour,imin,isec) 20 end 21 when 'quarter' 22 imonth += 3 23 if imonth <= 12 then 24 t1 = Time.local(iyear,imonth,iday,ihour,imin,isec) 25 else 26 t1 = Time.local(iyear+=1,imonth - 12,iday,ihour,imin,isec) 27 end 28 when 'years' 29 t1 = Time.local(iyear+i,imonth,iday,ihour,imin,isec) 30 else 31 raise 'not a valid date unit' 32 end 33 t1 34 end
1 2 date_add("17/03/2008 17:48:00",'months',2)
output: Sat May 17 17:48:00 +0100 2008