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

Creating a DateTime object with Ruby (See related posts)

This example creates a date and time variable which represents 22nd March 2008 4:30pm and 12 seconds.
d2 = DateTime.new(y=200,m=3,d=22, h=16,min=30,s=12)

or convert a date string into a DataTime object:
"17/03/2009 17:48:00"[/(\d+)\/(\d+)\/(\d+)\s(\d+):(\d+):(\d+)/]
d2 = DateTime.new(y=$3.to_i,m=$2.to_i,d=$1.to_i, h=$4.to_i,min=$5.to_i,s=$6.to_i)

or convert a date string into a Time object:
"22/03/2008 17:48:00"[/(\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
twork = Time.local(iyear,imonth,iday,ihour,imin,isec) 
puts 'we still have time to party' if Time.now < twork 

Reference:
Class: DateTime [ruby-doc.org]
Class: Time [ruby-doc.org]

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts