wallyfoo

wallyfoo

Need help understanding Timex, date structures, converting timezones, local presentation

This has been vexing me for a couple of days now, and I finally had a breakthrough. When I’m done with the explanation, please tell me: is this just obvious on the face of it? Or does this really not make sense with what Timex should be doing for me?

I am making a tool that I know is going to be used in the “America/Chicago” timezone. This is a very old database that has had a number of improvements and iterations over the years, and for reasons long forgotten, the inserted_at and updated_at are being stored as “timestamp(0) without time zone”. So, timestamps are being returned from the database as naive:

~N[2025-08-22 16:35:54]

I was taking this sigil and passing it directly to Timex to represent it in CST/CDT and format accordingly. Everyone using this app is going to be sitting in the same room in Texas for one week of the year.

~N[2025-08-22 16:35:54] 
|> Timex.to_datetime("America/Chicago") 
|> Timex.format!("{M}/{D}/{YYYY} {h12}:{m} {AM}")

“8/22/2025 4:35 PM”

Wait a second. That’s just the naive date time formatted. I absolutely expected Timex to cope with this. When I inspect the Timex.to_datetime(“America/Chicago”) line in this one, I get what looks correct: #DateTime<2025-08-22 16:35:54-05:00 CDT America/Chicago>

~N[2025-08-22 16:35:54] 
|> DateTime.from_naive!("Etc/UTC")
|> Timex.to_datetime("America/Chicago") 
|> Timex.format!("{M}/{D}/{YYYY} {h12}:{m} {AM}")

“8/22/2025 11:35 AM” ← this is the correct time in Texas from the starting point.

Explicitly casting to UTC first gets the correct result from Timex. In fact, if I swap the Datetime.from_naive/2 to Timex.to_datetime/1, the final result is the local central time (correct). Or when I do Timex.to_datetime(“Etc/UTC”) first. When I go straight from naive to the America/Chicago timezone, the formatting in the final step is for the NaiveDateTime.

This doesn’t feel correct. So, please tell me why I’m dumb.

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

So I think the part you’re missing is that you’re expecting it to treat a naive date time as if it’s in UTC by default. The whole point of NaiveDateTime is that it has zero timezone information at all. So the first thing you need to do is say “I’m telling you that these digits are a utc timezone date time” then you can go “now convert this to the equivalent time in Chicago”.

Your first attempt was saying “I’m telling you that these digits are Chicago time”.

10
Post #2

Also Liked

adamu

adamu

Worth mentioning that you don’t need Timex for this:

~N[2025-08-22 16:35:54]
|> DateTime.from_naive!("Etc/UTC")
|> DateTime.shift_zone!("America/Chicago")
|> Calendar.strftime("%-m/%-d/%Y %I:%M %p")
"8/22/2025 11:35 AM"

Additionally, if you are using Ecto, you can probably set the schema to utc_datetime to get a DateTime in UTC, allowing you to skip the naive datetime.

11
Post #4
annad

annad

I highly recommend that you check out TzDatetime. It made my life so much easier when it comes to date/times. It can be a serious rabbit hole when have to start dealing with daylight savings. This library handles it for you. I end up storing both the naive datetime, utc datetime and offset. The user always sees the time in their naive datetime and the UTC is used for translating the datetime to other people’s timezones (I’m dealing with international events so this was critical).

garrison

garrison

Keep in mind that, as the examples in the docs show, it is possible for the conversion from NaiveDateTime to DateTime to actually fail if the date/time do not actually exist in that timezone (e.g. due to daylight savings). You are avoiding that can of worms by storing UTC.

I recommend going for utc_datetime_usec instead (see primitive types), which should really be the default (but can’t be changed now).

The first thing I do in any new Ecto project is set the default timestamps to utc_datetime_usec for schemas and migrations. It’s just easier to store them all with microsecond precision rather than worry about it.

Where Next?

Popular in Questions Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 43657 311
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36432 110
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 127536 1222
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement