Ecto stores timestamps as :naive_datetime

When you use your timestamps from your Ecto repository to show your user edit or store times of database elements, it might make sense to convert them to a specific time zone. Otherwise the user may feel that time has been saved incorrectly.

By default, Ecto creates and stores timestamps in :naive_datetime format, for reasons of backward compatibility.

:naive_datetime is like :utc_datetime, but without timezone information.

So, how to display a :naive_datetime in a time that is relevant to the user? Within one of our larger repositories using Elixir on the backend and React on the frontend we use the daysJS library to assist with date transformation in Javascript.

Import these libraries:

import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import tz from "dayjs/plugin/timezone”;

Set up daysJS:


// you can define a specific time zone, or guess the user's time zone:;

Then, when we pass the :naive_datetime into a dayjs wrapper, we need to append a “Z”, so that it knows to be time zone aware when displaying this time, for example as in here:

{dayjs(`${YourNaiveDatetime}Z`).format("DD.MM.YYYY H:mm")}

And voila. Your user now see this time stamp in a time meaningful to them, in relation to their local timezone.