Method: Date#to_fs
- Defined in:
- activesupport/lib/active_support/core_ext/date/conversions.rb
#to_fs(format = :default) ⇒ Object Also known as: to_formatted_s
Convert to a formatted string. See DATE_FORMATS for predefined formats.
This method is aliased to to_formatted_s
.
date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
date.to_fs(:db) # => "2007-11-10"
date.to_formatted_s(:db) # => "2007-11-10"
date.to_fs(:short) # => "10 Nov"
date.to_fs(:number) # => "20071110"
date.to_fs(:long) # => "November 10, 2007"
date.to_fs(:long_ordinal) # => "November 10th, 2007"
date.to_fs(:rfc822) # => "10 Nov 2007"
date.to_fs(:rfc2822) # => "10 Nov 2007"
date.to_fs(:iso8601) # => "2007-11-10"
Adding your own date formats to to_fs
You can add your own formats to the Date::DATE_FORMATS hash. Use the format name as the hash key and either a strftime string or Proc instance that takes a date argument as the value.
# config/initializers/date_formats.rb
Date::DATE_FORMATS[:month_and_year] = '%B %Y'
Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") }
49 50 51 52 53 54 55 56 57 58 59 |
# File 'activesupport/lib/active_support/core_ext/date/conversions.rb', line 49 def to_fs(format = :default) if formatter = DATE_FORMATS[format] if formatter.respond_to?(:call) formatter.call(self).to_s else strftime(formatter) end else to_s end end |