Skip to main content
Photo by Mick Haupt via Unsplash

Print ordinal date suffixes (1st/2nd/3rd/4th) in GoHugo

Golangs $date.Format is unable to add ordinal suffixes to dates (like 1st, 2nd, 3rd, 4th). Let’s not judge Golang for that. The following is how I remedy this issue:

layouts/partials/func/formatOrdinalDate.html

 1{{- $format := .format -}}
 2{{- $date := .date -}}
 3{{- $shortened := "th" -}}
 4{{- if in (slice 1 21 31) $date.Day -}}
 5  {{- $shortened = "st" -}}
 6{{- else if in (slice 2 22) $date.Day -}}
 7  {{- $shortened = "and" -}}
 8{{- else if in (slice 3 23) $date.Day -}}
 9  {{- $shortened = "rd" -}}
10{{- end }}
11{{- return $date.Format (printf $format $shortened) -}}

call to this partial:

 1<span title="{{-
 2  with partialCached
 3    "func/formatOrdinalDate" (
 4        dict
 5            "format" "January 2%s, 2006 at 15:04 UTCMST:00"
 6            "date" .Lastmod .Lastmod
 7    )
 8  -}}
 9  {{- . -}}
10{{- end -}}">

Inside of the format string you can use whatever formatting you want to display based on what Golang understands as date format string. Then add a %s at the location where you wish to have the ordinal suffix.

And that’s that.

Back to top
Back Forward