| Module | ActiveSupport::CoreExtensions::Time::Conversions |
| In: |
vendor/rails/activesupport/lib/active_support/core_ext/time/conversions.rb
|
Getting times in different convenient string representations and other objects
| DATE_FORMATS | = | { :db => "%Y-%m-%d %H:%M:%S", :time => "%H:%M", :short => "%d %b %H:%M", :long => "%B %d, %Y %H:%M", :long_ordinal => lambda { |time| time.strftime("%B #{time.day.ordinalize}, %Y %H:%M") }, :rfc822 => "%a, %d %b %Y %H:%M:%S %z" |
# File vendor/rails/activesupport/lib/active_support/core_ext/time/conversions.rb, line 15
15: def self.included(base)
16: base.class_eval do
17: alias_method :to_default_s, :to_s
18: alias_method :to_s, :to_formatted_s
19: end
20: end
Convert a Time object to a Date, dropping hour, minute, and second precision.
my_time = Time.now
# => Mon Nov 12 22:59:51 -0500 2007
my_time.to_date
#=> Mon, 12 Nov 2007
your_time = Time.parse("1/13/2009 1:13:03 P.M.")
# => Tue Jan 13 13:13:03 -0500 2009
your_time.to_date
# => Tue, 13 Jan 2009
# File vendor/rails/activesupport/lib/active_support/core_ext/time/conversions.rb, line 64
64: def to_date
65: ::Date.new(year, month, day)
66: end
Converts a Time instance to a Ruby DateTime instance, preserving UTC offset.
my_time = Time.now
# => Mon Nov 12 23:04:21 -0500 2007
my_time.to_datetime
# => Mon, 12 Nov 2007 23:04:21 -0500
your_time = Time.parse("1/13/2009 1:13:03 P.M.")
# => Tue Jan 13 13:13:03 -0500 2009
your_time.to_datetime
# => Tue, 13 Jan 2009 13:13:03 -0500
# File vendor/rails/activesupport/lib/active_support/core_ext/time/conversions.rb, line 88
88: def to_datetime
89: ::DateTime.civil(year, month, day, hour, min, sec, Rational(utc_offset, 86400))
90: end
Convert to a formatted string - see DATE_FORMATS for predefined formats. You can also add your own formats to the DATE_FORMATS constant and use them with this method.
This method is also aliased as to_s.
time = Time.now # => Thu Jan 18 06:10:17 CST 2007 time.to_formatted_s(:time) # => "06:10:17" time.to_s(:time) # => "06:10:17" time.to_formatted_s(:db) # => "2007-01-18 06:10:17" time.to_formatted_s(:short) # => "18 Jan 06:10" time.to_formatted_s(:long) # => "January 18, 2007 06:10" time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10" time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
# File vendor/rails/activesupport/lib/active_support/core_ext/time/conversions.rb, line 38
38: def to_formatted_s(format = :default)
39: if formatter = DATE_FORMATS[format]
40: if formatter.respond_to?(:call)
41: formatter.call(self).to_s
42: else
43: strftime(formatter)
44: end
45: else
46: to_default_s
47: end
48: end