提交 66bde4ca 编写于 作者: J Jeremy Kemper

DateTime uses Time formats. Closes #8476.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6854 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
上级 26f88892
......@@ -3,22 +3,13 @@ module CoreExtensions #:nodoc:
module DateTime #:nodoc:
# Getting datetimes in different convenient string representations and other objects
module Conversions
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 { |datetime| datetime.strftime("%B #{datetime.day.ordinalize}, %Y %H:%M") },
:rfc822 => "%a, %d %b %Y %H:%M:%S %z",
}
def self.included(klass)
klass.send(:alias_method, :to_datetime_default_s, :to_s)
klass.send(:alias_method, :to_s, :to_formatted_s)
end
def to_formatted_s(format = :default)
if formatter = DATE_FORMATS[format]
if formatter = ::Time::DATE_FORMATS[format]
if formatter.respond_to?(:call)
formatter.call(self).to_s
else
......
......@@ -11,6 +11,12 @@ def test_to_s
assert_equal "Mon, 21 Feb 2005 14:30:00 +0000", datetime.to_s(:rfc822)
assert_equal "February 21st, 2005 14:30", datetime.to_s(:long_ordinal)
end
def test_custom_date_format
Time::DATE_FORMATS[:custom] = '%Y%m%d%H%M%S'
assert_equal '20050221143000', DateTime.new(2005, 2, 21, 14, 30, 0).to_s(:custom)
Time::DATE_FORMATS.delete(:custom)
end
def test_to_date
assert_equal Date.new(2005, 2, 21), DateTime.new(2005, 2, 21).to_date
......
......@@ -281,6 +281,12 @@ def test_to_s
time = Time.utc(2005, 2, 21, 17, 44, 30)
assert_equal "Mon, 21 Feb 2005 17:44:30 +0000", time.to_s(:rfc822)
end
def test_custom_date_format
Time::DATE_FORMATS[:custom] = '%Y%m%d%H%M%S'
assert_equal '20050221143000', Time.local(2005, 2, 21, 14, 30, 0).to_s(:custom)
Time::DATE_FORMATS.delete(:custom)
end
def test_to_date
assert_equal Date.new(2005, 2, 21), Time.local(2005, 2, 21, 17, 44, 30).to_date
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册