Permalink
Browse files

Add Time#to_s(:iso8601) for easy conversion of times to the iso8601 f…

…ormat for easy Javascript date parsing
  • Loading branch information...
1 parent 5861732 commit b67a80de9b55f91feb1c1056824f456710a96d0d @dhh dhh committed Jul 28, 2013
@@ -1,3 +1,7 @@
+* Add Time#to_s(:iso8601) for easy conversion of times to the iso8601 format for easy Javascript date parsing.
+
+ *DHH*
+
* Improve `ActiveSupport::Cache::MemoryStore` cache size calculation.
The memory used by a key/entry pair is calculated via `#cached_size`:
@@ -16,7 +16,8 @@ class Time
:rfc822 => lambda { |time|
offset_format = time.formatted_offset(false)
time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}")
- }
+ },
+ :iso8601 => "%Y-%m-%dT%H:%M:%SZ"
@pixeltrix
pixeltrix Jul 29, 2013 Member

This assumes that the time is in UTC - we need to take account of the offset here. Two ways we can do it:

:iso8601 => lambda { |time| time.iso8601 }

or

:iso8601 => lambda { |time| time.getutc.iso8601 }

The former returns a string with the correct offset and the latter returns a string with the correct UTC time. I'm assuming that you'd prefer the latter?

@dhh
dhh via email Jul 29, 2013 Member
@pixeltrix
pixeltrix Jul 29, 2013 Member

Whichever you prefer is fine.

I'd go with the former since you can always convert it to UTC yourself if you need it, e.g. time.getutc.to_s(:iso8601)

@dhh
dhh via email Jul 29, 2013 Member
}
# Converts to a formatted string. See DATE_FORMATS for builtin formats.
@@ -503,6 +503,7 @@ def test_to_s
assert_equal "20050221174430123456789", time.to_s(:nsec)
assert_equal "February 21, 2005 17:44", time.to_s(:long)
assert_equal "February 21st, 2005 17:44", time.to_s(:long_ordinal)
+ assert_equal "2009-02-05T14:30:05Z", Time.local(2009, 2, 5, 14, 30, 5).to_s(:iso8601)
with_env_tz "UTC" do
assert_equal "Mon, 21 Feb 2005 17:44:30 +0000", time.to_s(:rfc822)
end

0 comments on commit b67a80d

Please sign in to comment.