Skip to content

Feat: Useful.now_str/1 a simple string representation of the DateTime e.g: "2022-05-17 04:20" #13

@nelsonic

Description

@nelsonic

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_found

Why? 🤷‍♂️

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

The 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
image

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

Metadata

Metadata

Assignees

Labels

T1hTime Estimate 1 Hourchorea tedious but necessary task often paying technical debtenhancementNew feature or requesthelp wantedExtra attention is neededpriority-2Second highest priority, should be worked on as soon as the Priority-1 issues are finishedresearchResearch required; be specific

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions