A Ruby current date and time example

Ruby current date/time FAQ: How can I determine the current date and time in a Ruby script?

You can create a Time object in Ruby to represent the current date/time by calling the Time.now method, like this:

date = Time.now

After that, you can call the methods of the Time class (like year, month, hour, etc.) to get the data you need. Here is some sample code from an irb session where I explore the method of a Time object:

>> date = Time.now
=> Sat May 02 18:55:08 -0400 2009
>> date.year
=> 2009
>> date.month
=> 5
>> date.hour
=> 18
>> date.min
=> 55
>> date.sec
=> 8

Converting to gmtime

You can convert your Time object to gmtime by invoking the gmtime method. This irb session shows the output from my Time object before and after I call the gmtime method:

>> date = Time.now
=> Sat May 02 19:02:48 -0400 2009
>> date.hour
=> 19

# now call time#gmtime
>> date.gmtime
=> Sat May 02 23:02:48 UTC 2009
>> date.hour
=> 23