Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting UTC timestamp to ISO 8601 in Ruby

I have a timestamp that is in UTC

"2010-10-25 23:48:46 UTC"

I need to convert it into ISO 8601

"2010-10-29 06:09Z"

The documentation is confusing as hell - what is the easiest way to do that?

like image 249
meow Avatar asked Oct 30 '10 02:10

meow


People also ask

Does ISO 8601 use UTC?

ISO 8601 applies to these representations and formats: dates, in the Gregorian calendar (including the proleptic Gregorian calendar); times, based on the 24-hour timekeeping system, with optional UTC offset; time intervals; and combinations thereof.

How do I set timezone in ISO 8601?

ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).

Is ISO 8601 valid?

Yes it is a valid ISO 8601 date.


1 Answers

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.

like image 84
Ryan Bigg Avatar answered Oct 05 '22 01:10

Ryan Bigg