Print ordinal date suffixes (st/nd/rd/th)

QUICKTIPORDINALSDATEFORMAT

Last Modified: April 14, 2021

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

{{- $format := .format -}}
{{- $date := .date -}}
{{- $shortend := "th" -}}
{{- if in (slice 1 21 31) $date.Day -}}
  {{- $shortend = "st" -}}
{{- else if in (slice 2 22) $date.Day -}}
  {{- $shortend = "nd" -}}
{{- else if in (slice 3 23) $date.Day -}}
  {{- $shortend = "rd" -}}
{{- end }}
{{- return $date.Format (printf $format $shortend) -}}

call to this partial:

<span title="{{- 
  with partialCached 
    "func/formatOrdinalDate" (
        dict 
            "format" "January 2%s, 2006 at 15:04 UTCMST:00" 
            "date" .Lastmod .Lastmod 
    ) 
  -}}
  {{- . -}}
{{- 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.