Print UK Date Format for Post Date

When making this site, we wanted to show the date (above the title) in the British format by putting the day before the month. Controversial, I know. This also means including the date ordinal/suffix after the day, e.g. th, st and nd.

If you were writing this format in PHP it would look like this:

1
jS M Y

With the ‘S’ standing for:

English ordinal suffix for the day of the month, 2 characters

This is what we were trying to recreate when using Hugo, but it’s a bit tricky as Hugo is built on Go’s time formatting - which doesn’t have support for this suffix style. Because of this, we have to do the logic ourselves by working out the day and based on if it’s in certain lists (slices), show the correct text.

1
2
3
4
5
6
{{ .Date.Format "2" }}
{{- if in (slice 1 21 31) .Date.Day -}}st
{{- else if in (slice 2 22) .Date.Day -}}nd
{{- else if in (slice 3 23) .Date.Day -}}rd
{{- else -}}th
{{ end }} of {{ .Date.Format "January" }}, {{ .Date.Format "2006" }}

Which then prints the date to the page like this:

1
1st January, 2000

This code is based on the example in the Hugo docs. Thanks D Jenkins in the comments for a neater version (removing whitespace).