Converting UTC timestamp to ISO 8601 in Ruby Converting UTC timestamp to ISO 8601 in Ruby ruby ruby

Converting UTC timestamp to ISO 8601 in Ruby


I think you're trying to trick us.

The input date to your question is the 25th of October, 2010, whilst the output is the 29th of October, 2010. Well played!

Continuing on this nit-picking thread: your times are also completely different and you're missing the seconds from the output time.

Now for the true answer.

A little factoid first though: the ISO 8601 output in Ruby is similar to the "Combined date and time" output from ISO 8601's Wikipedia page.

You've got a string and so you'll need to convert it into a Time object which you can do with to_time. Then it's simply a matter of calling iso8601 on that object to get the ISO 8601 version:

"2010-10-25 23:48:46 UTC".to_time.iso8601

The to_time method is courtesy of Rails, whilst the iso8601 is courtesy of Ruby's standard library.


After much experimenting, I find the Time library's parser to be better than DateTime, although the reasons escape me at the moment. With that caveat, I always use Time rather than DateTime for this kind of stuff, and the ruby documentation is also difficult to grok as to why this is so,

require 'time'puts Time.parse("2010-10-25 23:48:46 UTC").iso8601"2010-10-25T23:48:46Z"


Note: you have to convert (parse) a time string into a time object before you can apply the to_time method.

ruby-1.9.2-p180 :016 > "2010-10-25 23:48:46 UTC".to_time.iso8601NoMethodError: undefined method `to_time' for "2010-10-25 23:48:46 UTC":String    from (irb):16

Correct procedure:

irb> ut = DateTime.parse("2010-10-25 23:48:46 UTC")irb> ut.iso8601 => "2010-10-25T23:48:46+00:00"