-
Notifications
You must be signed in to change notification settings - Fork 6
Description
Context
I just want a simple function that I can use to display the full human friendly date + time in my logs or UI.
e.g: "2022-04-20 04:20"
Why does it have to be so hard?! 🤷♂️
At present in Elixir (v1.13 latest), the native DateTime library doesn't have an easy way of doing this.
here are the docs for the DateTime.html.now!/2 function:
datetime = DateTime.now!("Etc/UTC")
datetime.time_zone
"Etc/UTC"
DateTime.now!("Europe/Copenhagen")
** (ArgumentError) cannot get current datetime in "Europe/Copenhagen" time zone, reason: :utc_only_time_zone_database
DateTime.now!("bad timezone", FakeTimeZoneDatabase)
** (ArgumentError) cannot get current datetime in "bad timezone" time zone, reason: :time_zone_not_foundWhy? 🤷♂️
Why on earth does a DateTime library not have sensible defaults?!
Why do I need to give a time_zone and time_zone_database just to use this function?!
Why does a person who is new to Elixir have to read documentation to understand this?!
At present this is how I'm forced to do it:
# Current date time e.g. "2022-04-20 04:20"
now = DateTime.utc_now |> DateTime.to_string |> String.split(".") |> List.firstThe problem is this is UTC ("Coordinated Universal Time") which I don't care about because it's not adjusted for daylight saving time i.e. behind by 1 hour.
What I want is:
Useful.now_str()
> "2022-04-20 04:20"The timezone could be optional.
e.g:
Useful.now_str("Europe/Zurich")But it could also be inferred from where the computer running the code or the user viewing the page is!!
Research/Reading
ElixirConf 2019 - Date, Time, and Time Zones in Elixir 1.9 - Lau Taarnskov: https://youtu.be/_E988mvPIzU

This forum thread: https://elixirforum.com/t/ecto-and-timezones/3276 suggests: https://github.com/lau/calecto
Which in turn uses: https://hexdocs.pm/calendar/readme.html