You want to print a date object as a string.
If you just want to look at a date, you can call
Date#to_s and not bother with fancy
require 'date' Time.now.to_s # => "Sat Mar 18 19:05:50 EST 2006" DateTime.now.to_s # => "2006-03-18T19:05:50-0500"
If you need the date in a specific format, you'll need to define
that format as a string containing time-format directives. Pass the
format string into
Date#strftime. You'll get back a
string in which the formatting directives have been replaced by the
correpsonding parts of the
A formatting directive looks like a percent sign and a letter:
%x. Everything in a format string
that's not a formatting directive is treated as a literal:
Time.gm(2006).strftime('The year is %Y!') # => "The year is 2006!"
The Discussion lists all the time formatting directives defined
Date#strftime. Here are some common
time-formatting strings, shown against a sample date of about 1:30 in
the afternoon, GMT, on the last day of 2005:
time = Time.gm(2005, 12, 31, 13, 22, 33) american_date = '%D' time.strftime(american_date) # => "12/31/05" european_date = '%d/%m/%y' time.strftime(european_date) # => "31/12/05" four_digit_year_date = '%m/%d/%Y' time.strftime(four_digit_year_date) # => "12/31/2005" date_and_time = '%m-%d-%Y %H:%M:%S %Z' time.strftime(date_and_time) # => "12-31-2005 13:22:33 GMT" twelve_hour_clock_time = '%m-%d-%Y %I:%M:%S %p' time.strftime(twelve_hour_clock_time) ...