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.

10
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.

wallyfoo

wallyfoo

I’ll gladly leave my brainfart here in case someone else runs into this, and they don’t know why. Thanks!

wallyfoo

wallyfoo

I appreciate you pointing this out. Timex is another tool I had in the dependencies from decisions made years ago. If you give a kid a hammer, the world becomes a nail, I suppose.

You’re also correct in the schema assertion. Setting @timestamps_optstimestamps_opts [type: :utc_datetime] in the schema or in the timestamps macro: timestamps(type: :utc_datetime) solves this problem as well.

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
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
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement