Working with Dates and Times in Ruby

From Techotopia
Revision as of 18:20, 4 December 2007 by Neil (Talk | contribs) (New page: Ruby provides a ''date'' library containing the ''Date'' and ''DateTime'' classes, designed to provide mechanisms for manipulating dates and times in Ruby programs. The purpose of this cha...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Ruby provides a date library containing the Date and DateTime classes, designed to provide mechanisms for manipulating dates and times in Ruby programs. The purpose of this chapter is to provide an overview of these classes.

Accessing the Date and DateTime Classes in Ruby

The Date and DateClass classes reside in the Ruby date library. Before these classes and their respective methods can be used, the date library must be included using the require directive:

require 'date'

Working with Dates in Ruby

Dates are handled in Ruby using the Date class. An instantiated Date object contains day, year and month values. A Date object may be initialized with day, month and year values on creation:

require 'date'

date = Date.new(2008, 12, 22)

date = Date.new(2008, 12, 22)
=> #<Date: 4909645/2,0,2299161>

Having created the date object we can access the properties of the object:

date.day
=> 22

date.month
=> 12

date.year
=> 2008

Working with Dates and Times

If both a date and a time value are needed, the DateTime class comes into use. As with the Date class, this class can similarly be pre-initialized on creation:

require 'date'

date = DateTime.new(2008, 12, 22, 14, 30)

Alternatively, the object can be configured to contain today's date and the current time:

date = DateTime.now

We can also calculate the difference between two date and times:

require 'date'

today = DateTime.now
=> #<DateTime: 441799066630193/180000000,-301/1440,2299161>

birthday = Date.new(2008, 4, 10)
=> #<Date: 4909133/2,0,2299161>

days_to_go = birthday - today

time_until = birthday - today
=> Rational(22903369807, 180000000)

time_until.to_i             # get the number of days until my birthday
=> 127

hours,minutes,seconds,frac = Date.day_fraction_to_time(time_until)
[3053, 46, 57, Rational(1057, 180000000)]

puts "It is my birthday in #{hours} hours, #{minutes} minutes and #{seconds} seconds (not that I am counting)"
It is my birthday in 3053 hours, 46 minutes and 57 seconds (not that I am counting)