Go, despite its robust standard library, does not support ordinal dates out of the box like ‘th’ and ‘st’. This makes producing dates in the format “1st January 2000” much harder - which we use a lot here in the UK. In this post we’ll aim to show how you can make this easier.
For reference, these are the options Go uses when chosing a new format:
1
Mon Jan 2 15:04:05 MST 2006
Our example below implements this for ourselves, as we create formatDateWithOrdinal() to print a given time in this format. This uses all three of the .Day() .Month() and .Year() functions within the time package, but passes the day through our extra function to add the ordinal.
packagemainimport("fmt""time")funcmain(){// Call our example:
fmt.Println("My Example Date:",formatDateWithOrdinal(time.Now()))}// formatDateWithOrdinal prints a given time in the format 1st January 2000.
funcformatDateWithOrdinal(ttime.Time)string{returnfmt.Sprintf("%s %s %d",addOrdinal(t.Day()),t.Month(),t.Year())}// addOrdinal takes a number and adds its ordinal (like st or th) to the end.
funcaddOrdinal(nint)string{switchn{case1,21,31:returnfmt.Sprintf("%dst",n)case2,22:returnfmt.Sprintf("%dnd",n)case3,23:returnfmt.Sprintf("%drd",n)default:returnfmt.Sprintf("%dth",n)}}
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.