to_formatted_s
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3 (0)
- 2.1.0 (0)
- 2.2.1 (0)
- 2.3.8 (0)
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
to_formatted_s(format = :default)
public
Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.
This method is aliased to to_s.
Examples
datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000 datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00" datetime.to_s(:db) # => "2007-12-04 00:00:00" datetime.to_s(:number) # => "20071204000000" datetime.to_formatted_s(:short) # => "04 Dec 00:00" datetime.to_formatted_s(:long) # => "December 04, 2007 00:00" datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00" datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
Adding your own datetime formats to to_formatted_s
DateTime formats are shared with Time. You can add your own to the Time::DATE_FORMATS hash. Use the format name as the hash key and either a strftime string or Proc instance that takes a time or datetime argument as the value.
# config/initializers/time_formats.rb Time::DATE_FORMATS[:month_and_year] = "%B %Y" Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
Format not coming out properly?
Date, Time and DateTime may have different formats defined.
If you do:
@user.created_at.to_formatted_s(:long_ordinal)
You will get (or something):
April 16th, 2009 22:03
But if you do:
@user.created_at.to_date.to_formatted_s(:long_ordinal)
You will get:
April 16th, 2009
So, be sure you know which one you are working with.
W3CDTF Format
Here is the formatted string for the W3CDTF datetime format (http://www.w3.org/TR/NOTE-datetime). It has a semicolon in the timezone part, therefore you cannot use ā%zā:
Time::DATE_FORMATS[:w3cdtf] = lambda { |time| time.strftime("%Y-%m-%dT%H:%M:%S#{time.formatted_offset}") }