Changes

Working with Dates and Times in Ruby

2,156 bytes added, 18:20, 4 December 2007
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...
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:

<pre>
require 'date'
</pre>

== 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:

<pre>
require 'date'

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

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

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

<pre>
date.day
=> 22

date.month
=> 12

date.year
=> 2008
</pre>

== 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:

<pre>
require 'date'

date = DateTime.new(2008, 12, 22, 14, 30)
</pre>

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

<pre>
date = DateTime.now
</pre>

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

<pre>
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)
</pre>