When working with Ecto.Date for things that have a visible date, they are not the most reader-friendly. It’s often nicer to format them in a way, such as “Sep 26th, 2024.”
Unfortunately, Elixir’s built-in Calendar.strftime/2 doesn’t provide a simple way to add day suffixes (like “st,” “nd,” “rd,” or “th”) to dates. This means that we need to write a custom function to handle this formatting.
defmodule DateUtils do
def format_date_with_suffix(date) do
day_with_suffix = add_ordinal_suffix(date.day)
Calendar.strftime(date, "%b #{day_with_suffix}, %Y")
end
defp add_ordinal_suffix(day) when day in [11, 12, 13], do: "#{day}th"
defp add_ordinal_suffix(day) do
suffix =
case rem(day, 10) do
1 -> "st"
2 -> "nd"
3 -> "rd"
_ -> "th"
end
"#{day}#{suffix}"
end
end
The following will give a public function DateUtils.format_date_with_suffix/1
and given we provide it a Ecto.Date it should render our expected result.
iex(1)> DateUtils.format_date_with_suffix(~D[2023-05-10])
-> "May 10th, 2023"