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.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With