Ruby/Rails: converting a Date to a UNIX timestamp

igul222 picture igul222 · Nov 26, 2009 · Viewed 176.1k times · Source

How would I get a UNIX timestamp (number of seconds since 1970 GMT) from a Date object in a Rails app?

I know Time#to_i returns a timestamp, but doing Date#to_time and then getting the timestamp results in something that's off by about a month (not sure why...).

Any help is appreciated, thanks!

Edit: OK, I think I figured it out- I was processing a date several times in a loop, and each time the date was moved a little because of a time zone mismatch, ultimately leading to my timestamp being a month off. Still, I'd be interested in knowing if there's any way to do this without relying on Date#to_time.

Answer

David Grayson picture David Grayson · Nov 26, 2009

The code date.to_time.to_i should work fine. The Rails console session below shows an example:

>> Date.new(2009,11,26).to_time
=> Thu Nov 26 00:00:00 -0800 2009
>> Date.new(2009,11,26).to_time.to_i
=> 1259222400
>> Time.at(1259222400)
=> Thu Nov 26 00:00:00 -0800 2009

Note that the intermediate DateTime object is in local time, so the timestamp might be a several hours off from what you expect. If you want to work in UTC time, you can use the DateTime's method "to_utc".