Cover by Leonard Richardson, Lucas Carlson

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

O'Reilly logo

3.3. Printing a Date

Problem

You want to print a date object as a string.

Solution

If you just want to look at a date, you can call Time#to_s or Date#to_s and not bother with fancy formatting:

	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 Time#strftime or Date#strftime. You'll get back a string in which the formatting directives have been replaced by the correpsonding parts of the Time or DateTime object.

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 by Time#strftime and 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) ...

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