---
title: How to convert Elixir's NaiveDateTime to Unix timestamp
date: '2023-06-06T00:00:00+00:00'
url: https://www.abhinav.co/how-to-convert-elixir-naivedatetime-to-unix-timestamp
summary: It is easy, but not very apparent
tags:
- Elixir
- Phoenix
- Swoosh
- Emaili
author: Abhinav Saxena
---

# 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
```elixir
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
- [NaiveDateTime on hexdocs](https://hexdocs.pm/elixir/1.12.3/NaiveDateTime.html)
