HUGO

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

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 partial "func/formatOrdinalDate" (dict "format" "January 2%s, 2006 at 15:04 UTCMST:00" "date" .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.

You can probably reduce this to one line with humanize.

Weird how that function can do two things instead of one…

Anyway, here is the changed version:

{{ $format := .format }}
{{ $date := .date }}
{{- $shortend := humanize $date.Day -}}
{{- return $date.Format (printf $format $shortend) -}}

hmm… nope. humanize gives me “1th” and “248th” in some cases. I prefer some more lines without issues :wink: I’ll check out humanize a bit more.

You are passing the wrong value to your partial.

If this is your partial:

{{ $format := .format }}
{{ $date := .date }}
{{- $shortend := humanize $date.Day -}}
{{- return $date.Format (printf $format $shortend) -}}

Pass it this:

dict "format" "January %s, 2006 at 15:04 UTCMST:00" "date" .Lastmod

Not this:

dict "format" "January 2%s, 2006 at 15:04 UTCMST:00" "date" .Lastmod

Further testing of humanize if you’re curious:

{{ range seq 1 248 }}
  {{ humanize . }}<br>
{{ end }}
1 Like

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