Is there a better way to translate a date with Timex?

Using Timex, I’m trying to translate a date from “October 2024” to “Octubre 2024” (spanish).

This works:

<% [month, year] =
  Date.utc_today()
  |> Timex.shift(months: 9)
  |> Timex.format!("{Mfull} {YYYY}") # October 2024
  |> String.split(" ") %>

<%= "#{Timex.Translator.translate("es", "months", month)} #{year}" %>

Is there a better way to translate dates in Elixir?

Maybe using DateTimeParser — DateTimeParser v1.2.0 to parse the first string, and then Date and Time Localization and Formatting — Cldr Dates & Times v2.16.0 to format/localise.

1 Like

With Elixir 1.17 (released in April) you can:

Date.utc_today()
|> Date.shift(month: 9)
|> Cldr.Date.to_string(format: "MMMM yyyy", locale: :es)
{:ok, "octubre 2024"}

Of course Timex is also still very useful.

ex_cldr_dates_times has a lot of formatting symbols so you should be able to format to your requirements. (I’m the author).

8 Likes