timex
timex copied to clipboard
Recommended way to add ordinal suffix for the day of month?
I cannot find the ordinal suffix for the month in the Timex.Format.DateTime.Formatter module. Similar to what PHP has for their datetime: English ordinal suffix for the day of the month, 2 characters | st, nd, rd or th. http://php.net/manual/en/function.date.php
Is a custom formatter recommended to add the suffix?
For now I created this module to get the suffix and then I put the result in the Timex.format call.
defmodule OrdinalSuffix do
def get(i) do
value = elem(Integer.parse(i), 0)
j = div(value, 10)
k = div(value, 100)
cond do
j == 1 && k != 11 ->
"st"
j == 2 && k != 12 ->
"nd"
j == 3 && k != 13 ->
"rd"
true ->
"th"
end
end
end
I call it with this:
sample_date = {2016,3,4}
month = Timex.format(sample_date, "{D}")
suffix = OrdinalSuffix.get(elem(month, 1))
Timex.format(sample_date, "{YYYY}-{0M}-{D}" <> suffix)
I'm open to extending the formatter with a new token, if you would like to submit a PR!