When dealing with time zones in Elixir, the tzdata
library provides reliable timezone support based on the IANA Time Zone Database. Hereβs how to integrate and use it in your project.
Add the dependency
First, include the tzdata
library in your mix.exs
:
{:tzdata, "~> 1.1"}
Then run:
mix deps.get
Configure it globally
Set tzdata
as the default timezone database in your config:
config/config.exs
config :elixir, :time_zone_database, Tzdata.TimeZoneDatabase
This allows the DateTime
module to use it for timezone conversions.
Usage example
To shift a UTC datetime (e.g. from your Ecto schema) to a specific timezone and format it:
{item.inserted_at
|> DateTime.shift_zone!("Europe/Brussels")
|> Calendar.strftime("%Y-%m-%d %H:%M")}
This ensures your datetimes are correctly localized and displayed according to the desired timezone.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.