1 module ActiveSupport
#:nodoc:
2 module CoreExtensions
#:nodoc:
4 # Converting dates to formatted strings, times, and datetimes.
11 :long_ordinal => lambda
{ |date
| date
.strftime("%B #{date.day.ordinalize}, %Y") }, # => "April 25th, 2007"
15 def self.included(base
) #:nodoc:
17 alias_method
:to_default_s, :to_s
18 alias_method
:to_s, :to_formatted_s
19 alias_method
:default_inspect, :inspect
20 alias_method
:inspect, :readable_inspect
22 # Ruby 1.9 has Date#to_time which converts to localtime only.
23 remove_method
:to_time if base
.instance_methods
.include?(:to_time)
25 # Ruby 1.9 has Date#xmlschema which converts to a string without the time component.
26 remove_method
:xmlschema if base
.instance_methods
.include?(:xmlschema)
30 # Convert to a formatted string. See DATE_FORMATS for predefined formats.
32 # This method is aliased to <tt>to_s</tt>.
35 # date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
37 # date.to_formatted_s(:db) # => "2007-11-10"
38 # date.to_s(:db) # => "2007-11-10"
40 # date.to_formatted_s(:short) # => "10 Nov"
41 # date.to_formatted_s(:long) # => "November 10, 2007"
42 # date.to_formatted_s(:long_ordinal) # => "November 10th, 2007"
43 # date.to_formatted_s(:rfc822) # => "10 Nov 2007"
45 # == Adding your own time formats to to_formatted_s
46 # You can add your own formats to the Date::DATE_FORMATS hash.
47 # Use the format name as the hash key and either a strftime string
48 # or Proc instance that takes a date argument as the value.
50 # # config/initializers/time_formats.rb
51 # Date::DATE_FORMATS[:month_and_year] = "%B %Y"
52 # Date::DATE_FORMATS[:short_ordinal] = lambda { |date| date.strftime("%B #{date.day.ordinalize}") }
53 def to_formatted_s(format
= :default)
54 if formatter
= DATE_FORMATS
[format
]
55 if formatter
.respond_to
?(:call)
56 formatter
.call(self).to_s
65 # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
67 strftime("%a, %d %b %Y")
70 # A method to keep Time, Date and DateTime instances interchangeable on conversions.
71 # In this case, it simply returns +self+.
74 end if RUBY_VERSION < '1.9'
76 # Converts a Date instance to a Time, where the time is set to the beginning of the day.
77 # The timezone can be either :local or :utc (default :local).
80 # date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
82 # date.to_time # => Sat Nov 10 00:00:00 0800 2007
83 # date.to_time(:local) # => Sat Nov 10 00:00:00 0800 2007
85 # date.to_time(:utc) # => Sat Nov 10 00:00:00 UTC 2007
86 def to_time(form
= :local)
87 ::Time.send("#{form}_time", year
, month
, day
)
90 # Converts a Date instance to a DateTime, where the time is set to the beginning of the day
91 # and UTC offset is set to 0.
94 # date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
96 # date.to_datetime # => Sat, 10 Nov 2007 00:00:00 0000
98 ::DateTime.civil(year
, month
, day
, 0, 0, 0, 0)
99 end if RUBY_VERSION < '1.9'