BrightEyesDavid
From shifted DateTime to Cldr.DateTime.to_string/2
I have a UTC datetime from a timestamptz PostgreSQL column, and am trying to:
- convert it to the user’s timezone;
- output a localised string representation for the frontend.
I’m trying to use DateTime for 1 and Cldr.DateTime for 2.
iex> {:ok, shifted} = DateTime.shift_zone(~U[2024-07-13 21:33:23.163097Z], "Europe/Berlin")
{:ok, #DateTime<2024-07-13 23:33:23.163097+02:00 CEST Europe/Berlin>}
However, Cldr.DateTime.to_string/2 doesn’t accept #DateTime<...>:
iex> {:ok, result} = Cldr.DateTime.to_string(shifted, "en-GB")
** (MatchError) no match of right hand side value: {:error, {ArgumentError, "Invalid DateTime. DateTime is a map that contains at least :year, :month, :day, :hour, :minute, :second and :calendar. Found: #DateTime<2024-07-13 23:33:23.163097+02:00 CEST Europe/Berlin Cldr.Calendar.Gregorian>"}}
(stdlib 4.3.1.3) erl_eval.erl:496: :erl_eval.expr/6
iex:3: (file)
I don’t know what #...<...> means, exactly, or how to convert it to a DateTime struct/map that Cldr.DateTime can use. Thanks.
Marked As Solved
belaustegui
Looks like you are calling Cldr.DateTime.to_string incorrectly.
The locale must be passed as a keyword list. This should work:
{:ok, result} = Cldr.DateTime.to_string(shifted, locale: "en-GB")
Also Liked
kip
I’ve published ex_cldr_dates_times version 2.20.2 that improves the error message when options are not provided as a keyword list. Using your example:
iex> {:ok, shifted} = DateTime.shift_zone(~U[2024-07-13 21:33:23.163097Z], "Europe/Berlin")
{:ok, #DateTime<2024-07-13 23:33:23.163097+02:00 CEST Europe/Berlin>}
iex> Cldr.DateTime.to_string(shifted, "en-GB")
{:error,
{ArgumentError,
"Unexpected option value \"en-GB\". Options must be a keyword list"}}
Last Post!
BrightEyesDavid
@dimitarvp, @LostKobrakai, thanks. So the use of # seems to be related to a comment marker, as the representation is not valid Elixir syntax. In 1.17’s documentation: Inspect — Elixir v1.17.2. That mentions that #Name<...> tends to be used when there are private fields to hide. I guess in the case of DateTime it’s used for conciseness.
@kip, thanks, and thanks very much for your libraries!
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #elixirconf-us
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









