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

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 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.

   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

A simple loop in Ruby

This loop repeats 10 times, with each iteration it increments the variable 'i' by 1 and displays it's value.

   1  
   2  i = 0
   3  10.times do
   4    i += 1
   5    puts i
   6  end
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS