Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert an ISO 8601 date to a UNIX timestamp in Ruby?

I've been trying Time.parse() and Date.parse(), but can't see to figure it out.

I need to convert a date in the form "2007-12-31 23:59:59" to a UNIX timestamp. Something like PHP's strtotime() function would be perfect.

like image 762
Josh Fraser Avatar asked Dec 17 '22 21:12

Josh Fraser


2 Answers

The ISO 8601 time format for the example you give would be "2007-12-31T23:59:59", not "2007-12-31 23:59:59" (note the T between the data and time components).

In Ruby, if you require the time library, you can parse properly formatted ISO 8601 dates. If your dates are coming in with a space instead of a T to separate the date from the time, just replace it before passing it in to Time.iso8601:

>> require 'time'
=> true
>> Time.iso8601("2007-12-31 23:59:59".sub(/ /,'T'))
=> Mon Dec 31 23:59:59 -0500 2007

To convert a time in this format to a Unix timestamp, just use .to_i:

>> Time.iso8601("2007-12-31 23:59:59".sub(/ /,'T')).to_i
=> 1199163599

If you need more flexibility about the format, Time.parse should do the trick; I would be careful about using that in production code, however, because it might give unexpected values for malformed or invalid input, instead of throwing an exception.

like image 76
Brian Campbell Avatar answered May 08 '23 07:05

Brian Campbell


You have Time.strptime in Ruby 1.9 So in your case,

>> time = Time.strptime('2007-12-31 23:59:59', '%Y-%m-%d %H:%M:%S')     
=> 2007-12-31 23:59:59 +0000

Once you have a Time object, you can convert it to many formats. A simple time.to_i will give you a Unix Timestamp.

like image 36
Swanand Avatar answered May 08 '23 07:05

Swanand