How to convert a Date struct to an easily readable string?

Hi!

My goal is to convert the Date struct to an easily-readable string version of that date.

For example:

~D[2000-01-15] would be converted to “January 15th, 2024”.

Does anyone know of a function or library that already does this?

Thanks!!!

The function you’re looking for is this one: Calendar.strftime/3

That will let you pass in the date and then a format string in which you can specify things like the full name of the month, date, etc.

6 Likes

Suggestions on how to format the day of the month as an ordinal number?

Ex: August 1 as August 1st, August 2 as August 2nd, etc.

It could be implemented somewhere in Cldr.Calendars or Cldr.Numbers. If it isn’t, or if you’re not willing to add an extra dependency, writing your own implementation is straightforward:

def ending(day) when day in [1, 21, 31], do: "st"
def ending(day) when day in [2, 22], do: "nd"
def ending(day) when day in [3, 23], do: "rd"
def ending(_), do: "th"
3 Likes

I’ve just realized that the version of this function without function overloading would look a bit cleaner. However, I miss this killer feature of Elixir so much when programming in other languages that I sometimes find myself overusing it. :smile:

Nah :slight_smile: The below is the real overusing of Elixir killer features:

defmodule DayEnding do
  Enum.each(1..31, fn
    day when div(day, 10) == 1 -> def ending(unquote(day)), do: "th"
    day when rem(day, 10) == 1 -> def ending(unquote(day)), do: "st"
    day when rem(day, 10) == 2 -> def ending(unquote(day)), do: "nd"
    day when rem(day, 10) == 3 -> def ending(unquote(day)), do: "rd"
    day -> def ending(unquote(day)), do: "th"
  end)
end
4 Likes

ex_cldr_numbers can format ordinals, but CLDR does not maintain any date formats that include ordinal numbers.

iex> Cldr.Number.to_string 1, format: :ordinal
{:ok, "1st"}
iex> Cldr.Number.to_string 1, format: :ordinal, locale: :es
{:ok, "1.º"}
iex> Cldr.Number.to_string 1, format: :ordinal, locale: :zh
{:ok, "第1"}
2 Likes