How to convert Ecto.DateTime to UNIX timestamps?

You have to convert the Ecto.DateTime struct to the erlang tuple (via Ecto.DateTime.to_erl/1) and then use :calendar.datetime_to_gregorian_seconds to get the number of gregorian seconds (since day 0) and subtract the unix time in gregorian seconds (62167219200). In one (in)glorious pipeline:

datetime
|> Ecto.DateTime.to_erl
|> :calendar.datetime_to_gregorian_seconds
|> Kernel.-(62167219200)

And now you know exactly why we decided to add Calendar types in Elixir v1.3. :sweat_smile: I hope to soon get back to Ecto and migrate it to use the new Calendar types.

10 Likes