How to convert Elixir's NaiveDateTime to Unix timestamp

I recently spent more than 20 minutes trying to figure out how to convert NaiveDateTime to Unix timestamp. I tried ChatGPT and Google search without any luck. Fortunately, reading documentation helps and it was hiding somewhere in the docs.

Here is how you do it

iex> current_time = NaiveDateTime.utc_now()

iex> unix_epoch = ~N[1970-01-01 00:00:00]

iex> # Take a difference between current_time and unix_epoch (both are in NaiveDateTime format)
iex> NaiveDateTime.diff(current_time, unix_epoch)
1686099838

Reference

© 2023 Abhinav Saxena   •   Powered by Soopr   •   Theme  Moonwalk