O'Reilly logo

Learning Ruby by Michael Fitzgerald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Date and Time

Figuring out the day and time is important in daily life and in computing, so Ruby naturally offers facilities to do so. In this section, I'll talk about Ruby's Date and Time classes.

The Time Class

I cover many of the most commonly used Time methods here. See http://ruby-doc.org/core/classes/Time.html for documentation on all the Time methods.

To determine the current time, use the now method (or its synonym new) from Time. Calling the method twice can help you determine how much time has elapsed in between.

start = Time.now # => Tue Jan 30 04:12:50 -0700 2007
stop = Time.now # => Tue Jan 30 04:13:00 -0700 2007

To set a given time, use the local method (mktime is a synonym):

local_time = Time.local( 2007, "jan", 30, 1, 15, 20 )
# => Tue Jan 30 01:15:20 -0700 2007

The arguments to this call to local are (in order) year, month, date, hour, minutes, seconds. You can also call local with these arguments:

my_time = Time.local( 20, 15, 1, 30, "jan", 2007, 2, 30, false, "MST")
# => Tue Jan 30 01:15:20 -0700 2007

In this call, the arguments, in order, are seconds, minutes, hour, day, month, year, day of the week, day of the year, is-it-daylight-savings-time?, and timezone.

From a Time object you can get all kinds of particulars, such as the day, the day of the week, and the day of the year:

stop.day # the day of the month => 30
stop.yday # how many days so far this year => 30
stop.wday # the day of the week => 2, or Tue (Sun == 0)

You can retrieve the year, the month, and the timezone: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required