Reputation: 10268
I would like to produce formatted dates in a human-readable format. Typically in an English locale, suffixes are used for the day of the month, i.e. 1st, 2nd, 3rd, 4th, 5th and so on.
I tried using the format string "Monday 2nd January"
to format such dates but it doesn't appear to work.
E.g. in the playground:
import (
"fmt"
"time"
)
const format = "Monday 2nd January"
func main() {
t1 := time.Date(2015, 3, 4, 1, 1, 1, 1, time.UTC)
fmt.Println(t1.Format(format))
t2 := time.Date(2015, 3, 1, 1, 1, 1, 1, time.UTC)
fmt.Println(t2.Format(format))
}
This generates the result
Wednesday 4nd March
Sunday 1nd March
but I would expect
Wednesday 4th March
Sunday 1st March
What have I done wrong?
Upvotes: 4
Views: 1998
Reputation: 99351
It doesn't support that kind of formatting, you will have to implement it yourself, something (hacky) like this:
func formatDate(t time.Time) string {
suffix := "th"
switch t.Day() {
case 1, 21, 31:
suffix = "st"
case 2, 22:
suffix = "nd"
case 3, 23:
suffix = "rd"
}
return t.Format("Monday 2" + suffix + " January")
}
Upvotes: 8