简体   繁体   中英

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.

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.

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.

You can use 'date.to_time.to_i' to convert date time to unix timestamp.

Following is the output on rails console:-

date = Date.today => Thu, 23 Sep 2010 date => Thu, 23 Sep 2010 date.to_time.to_i => 1285180200

Thanks, Anubhaw

You can use the strftime method

date = Date.today #this will return Thu, 23 Sep 2010 str_date = date.strftime('%b %d %Y') # This will give Sep 23 2010

refer this for better understanding blog

This will help you to convert time in custom formats. But it won't work in your case ie converting it to UNIX timestamp.

Turned out all I needed was:

Time.parse(date_str).to_i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM