From f436ce8e7db5b5f8524c6769a91ecc7de36bff8f Mon Sep 17 00:00:00 2001 From: Jason Frey (Fryguy) Date: Fri, 5 Jun 2009 13:46:42 -0400 Subject: [PATCH 1/1] Added timezone and fractional seconds support to String-Date conversions. --- .../active_support/core_ext/string/conversions.rb | 8 ++++++-- activesupport/test/core_ext/string_ext_test.rb | 3 +++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb index 2b9f8c7..331416b 100644 --- a/activesupport/lib/active_support/core_ext/string/conversions.rb +++ b/activesupport/lib/active_support/core_ext/string/conversions.rb @@ -9,7 +9,9 @@ class String # Form can be either :utc (default) or :local. def to_time(form = :utc) - ::Time.send("#{form}_time", *::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec).map { |arg| arg || 0 }) + d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction).map { |arg| arg || 0 } + d[6] *= 1000000 + ::Time.send("#{form}_time", *d) end def to_date @@ -17,6 +19,8 @@ class String end def to_datetime - ::DateTime.civil(*::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec).map { |arg| arg || 0 }) + d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :sec_fraction).map { |arg| arg || 0 } + d[5] += d.pop + ::DateTime.civil(*d) end end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 237a843..6991b17 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -112,6 +112,8 @@ class StringInflectionsTest < Test::Unit::TestCase def test_string_to_time assert_equal Time.utc(2005, 2, 27, 23, 50), "2005-02-27 23:50".to_time assert_equal Time.local(2005, 2, 27, 23, 50), "2005-02-27 23:50".to_time(:local) + assert_equal Time.utc(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time + assert_equal Time.local(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time(:local) assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time assert_equal Time.local_time(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time(:local) end @@ -120,6 +122,7 @@ class StringInflectionsTest < Test::Unit::TestCase assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_datetime assert_equal 0, "2039-02-27 23:50".to_datetime.offset # use UTC offset assert_equal ::Date::ITALY, "2039-02-27 23:50".to_datetime.start # use Ruby's default start value + assert_equal DateTime.civil(2039, 2, 27, 23, 50, 19 + Rational(275038, 1000000), "-04:00"), "2039-02-27T23:50:19.275038-04:00".to_datetime end def test_string_to_date -- 1.6.1.9.g97c34