0

The time.Format() method will parse the argument January 2, 2006 into outputting June 20, 2021, but it won't parse January 2nd, 2006 into June 20th, 2021 and instead output June 20nd, 2021.

How could I tell it to use the right ordinal indiciator: st/nd/rd/th suffix? I don't see it mentioned in the documentation.

shmsr
  • 3,802
  • 2
  • 18
  • 29
Digital Ninja
  • 3,415
  • 5
  • 26
  • 51

2 Answers2

1

The support for the ordinal indicator is not there in the standard library. You can either implement the same yourself by taking help from this answer or use a third-party package.

There is a third-party package available for Go to convert the input integer to a string with the correct ordinal indicator; take a look at go-humanize.

Also, if you look under the hood at the implementation of go-humanize's support for the ordinal indicator; you'd notice that is very simple so I'd prefer maybe just implement it yourself by referring to both implementations I have linked. Refer: https://github.com/dustin/go-humanize/blob/v1.0.0/ordinals.go#L8

Or, go use go-humanize.

shmsr
  • 3,802
  • 2
  • 18
  • 29
1

To add right ordinal indicator: st/nd/rd/th suffix you can make use of switch case .I have created a sample program to print all days of month along with their respective suffixes as follows:

package main

import (
    "fmt"
)

func getDaySuffix(n int) string {

    if n >= 11 && n <= 13 {
        return "th"
    } else {

        switch n % 10 {
        case 1:
            return "st"
        case 2:
            return "nd"
        case 3:
            return "rd"
        default:
            return "th"
        }
    }
}

func main() {

    for i := 1; i < 32; i++ {
        suf := getDaySuffix(i)
        fmt.Println(i, suf)

    }

}

Output:

1 st
2 nd
3 rd
4 th
5 th
6 th
7 th
8 th
9 th
10 th
11 th
12 th
13 th
14 th
15 th
16 th
17 th
18 th
19 th
20 th
21 st
22 nd
23 rd
24 th
25 th
26 th
27 th
28 th
29 th
30 th
31 st
Gopher
  • 721
  • 3
  • 8