Hugo equivalent for Liquid syntax to add ordinal date suffixes

I am trying to port a simple Jekyll theme to Hugo. It uses the code below to show dates. Does anyone have an idea of what an equivalent in Hugo/Go would look like?

{% assign day = page.date | date: "%-d" %} {% case day %} {% when '1' or '21' or '31' %}{{ day }}st {% when '2' or '22' %}{{

day }}nd {% when '3' or '23' %}{{ day }}rd {% else %}{{ day }}th {% endcase %} {{ page.date | date: "of %B, %Y" }}
{{ humanize <variable with number string> }}

humanize

I found this solution. The long form works as expected, but the short ‘humanize’ one didn’t work as expected.

Golang’s date formatting does not have ordinals (1st, 2nd). That is the problem. Humanize works if it’s made clear to Go that it’s a number. printf with %s results in a typed string so humanize fails here. %d would work again I think.

Do you have a solution that makes the humanize string work? @davidsneighbour

This:

{{ $day := dateFormat "2" .Date }}
{{ humanize (int $day) }}

The .Date is of course the date that you want to display. Depends on the context and location of the snippet. First line returns the day as single integer, but in a string, second one types it as integer (or number in Go) and humanize likes it now.

Thanks. I haven’t tried this. If this is the case then either humanize needs to be fixed to accept numbers represented as strings or its documentation:

If the input is either an int64 value or the string representation of an integer, humanize returns the number with the proper ordinal appended.

I was asking in the context of this code how that will work.

{{ humanize 2 }}     --> 2nd
{{ humanize "2" }}   --> 2nd
{{ humanize 2.0 }}   --> 2nd
{{ humanize "2.0" }} --> 2.0

Works as documented.

You don’t need to convert Hugo dates into strings and then back into ints. You can use the methods on Go’s time.Time to get the ints out of them and pass that along to humanize:

{{ humanize .Page.PublishDate.Day }} → 1st
1 Like

From here.

{{ humanize $.PublishDate.Day }} {{ $.Date.Format "January, 2006" }}

If using .LastMod

{{ humanize $.Lastmod.Day }} {{ $.Lastmod.Format "January, 2006" }}

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.