instance method to_fs

Ruby on Rails 7.0.10

Since v7.0.10

Available in: v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

to_fs(format = :default)

Converts to a formatted string. See DATE_FORMATS for built-in formats.

This method is aliased to to_formatted_s.

time = Time.now                    # => 2007-01-18 06:10:17 -06:00

time.to_fs(:time)                  # => "06:10"
time.to_formatted_s(:time)         # => "06:10"

time.to_fs(:db)           # => "2007-01-18 06:10:17"
time.to_fs(:number)       # => "20070118061017"
time.to_fs(:short)        # => "18 Jan 06:10"
time.to_fs(:long)         # => "January 18, 2007 06:10"
time.to_fs(:long_ordinal) # => "January 18th, 2007 06:10"
time.to_fs(:rfc822)       # => "Thu, 18 Jan 2007 06:10:17 -0600"
time.to_fs(:iso8601)      # => "2007-01-18T06:10:17-06:00"

Adding your own time formats to to_fs

You can add your own formats 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 argument as the value.

# config/initializers/time_formats.rb
Time::DATE_FORMATS[:month_and_year] = '%B %Y'
Time::DATE_FORMATS[:short_ordinal]  = ->(time) { time.strftime("%B #{time.day.ordinalize}") }

Parameters

format opt = :default
Source
# File activesupport/lib/active_support/core_ext/time/conversions.rb, line 53
  def to_fs(format = :default)
    if formatter = DATE_FORMATS[format]
      formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
    else
      # Change to `to_s` when deprecation is gone. Also deprecate `to_default_s`.
      to_default_s
    end
  end

Defined in activesupport/lib/active_support/core_ext/time/conversions.rb line 53 · View on GitHub · Improve this page · Find usages on GitHub

Defined in Time

Type at least 2 characters to search.

↑↓ navigate · open · esc close