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 <
The suggested options of using to_utc
or utc
to fix the local time offset does not work. For me I found using Time.utc()
worked correctly and the code involves less steps:
> Time.utc(2016, 12, 25).to_i
=> 1482624000 # correct
vs
> Date.new(2016, 12, 25).to_time.utc.to_i
=> 1482584400 # incorrect
Here is what happens when you call utc after using Date
....
> Date.new(2016, 12, 25).to_time
=> 2016-12-25 00:00:00 +1100 # This will use your system's time offset
> Date.new(2016, 12, 25).to_time.utc
=> 2016-12-24 13:00:00 UTC
...so clearly calling to_i
is going to give the wrong timestamp.