HerrAusragend HerrAusragend - 2 years ago 211
Ruby Question

Ruby - Convert formatted date to timestamp

I need to convert a date string to the Unix timestamp format.
The string I get from an API looks like:


i get:

2015-05-27 07:39:59

which is a pretty regular date format. Nonetheless, Ruby isn't able to convert it to Unix TS format. I tried
but I keep getting

In PHP the function
just works perfectly for this.
Is there some similar method for Ruby?

Answer Source

Your date string is in RFC3339 format. You can parse it into a DateTime object, then convert it to Time and finally to a UNIX timestamp.

require 'date'

#=> #<DateTime: 2015-05-27T07:39:59+00:00 ((2457170j,27599s,0n),+0s,2299161j)>

#=> 2015-05-27 09:39:59 +0200

#=> 1432712399

For a more general approach, you can use DateTime.parse instead of DateTime.rfc3339, but it is better to use the more specific method if you know the format, because it prevents errors due to ambiguities in the date string. If you have a custom format, you can use DateTime.strptime to parse it

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download