lobo_tuerto's notes
for greatly improving DX
Blog
Notes
About

Parse Twitter's date format with Elixir

Sun Aug 15 14:15:50 +0000 2021 — How to parse something like this? Let's see.

📅Date15 August 2020
🏷️
elixirprogramming

Twitter’s API date format

If you are using Twitter’s API you’ve probably come across their particular way of formatting dates on user’s tweets:

created_at: "Sun Aug 15 14:15:50 +0000 2021",

Let’s see how we would parse that into something like this:

~U[2021-08-15 14:15:50Z]

Timex

For parsing we’re going to use Timex. Add this to you project dependencies:

  # ...
  defp deps do
    [
      {:timex, "~> 3.7"}
      # ...

Parse the date string

Let’s use the strftime date formatting language:

twitter_date = "Sun Aug 15 14:15:50 +0000 2021"

twitter_date
|> Timex.parse!("%a %b %d %H:%M:%S %z %Y", :strftime)
# ~U[2021-08-15 14:15:50Z]

We can use Timex own date formatting language too:

twitter_date = "Sun Aug 15 14:15:50 +0000 2021"

twitter_date
|> Timex.parse!("{WDshort} {Mshort} {D} {h24}:{m}:{s} {Z} {YYYY}")
# ~U[2021-08-15 14:15:50Z]

Alternatively you can skip parsing the timezone and thus get a naive datetime —with no timezone info— where you could do an extra step to convert it from NaiveDateTime to DateTime:

twitter_date = "Sun Aug 15 14:15:50 +0000 2021"

twitter_date
|> Timex.parse!("%a %b %d %H:%M:%S +0000 %Y", :strftime)
# ~N[2021-08-15 14:15:50] # no timezone information!
|> DateTime.from_naive!("Etc/UTC")
# ~U[2021-08-15 14:15:50Z]

References


Got comments or feedback?
Follow me on
rev-7175614