wallyfoo

wallyfoo

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.

Showing Posts 1 to 9

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 #1
wallyfoo

wallyfoo OP

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

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 #3
wallyfoo

wallyfoo OP

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.

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.

adamu

adamu

Just make sure that if something happens at 1AM on November 2, you pick the right 1AM to convert to UTC :one_o_clock::one_o_clock:

mudasobwa

mudasobwa

Creator of Cure

Well, technically it does not matter at all. To my best knowledge, nobody sets up a date in UTC time (pun intended,) maybe some freaks in TAI-land only (pun intended.)

So we are all good picking up any of these two representations, once they both represent an actual Nov 2, 1AM :stuck_out_tongue:

adamu

adamu

That’s what I mean, you need to pick one. When storing in UTC, you can’t guarantee that a date can be converted to UTC without resolving ambiguities.

iex(1)> DateTime.new(~D[2025-11-02], ~T[01:00:00], "America/Chicago")
{:ambiguous, #DateTime<2025-11-02 01:00:00-05:00 CDT America/Chicago>,
 #DateTime<2025-11-02 01:00:00-06:00 CST America/Chicago>}

Just pointing out that storing in UTC avoids one can of worms, but there are worms everywhere when it comes to handling time. :worm:

— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews