英文:
How to get the ordinal indicator using time.Format()?
问题
time.Format()
方法将解析参数January 2, 2006
并输出June 20, 2021
,但它不会将January 2nd, 2006
解析为June 20th, 2021
,而是输出June 20nd, 2021
。
我该如何告诉它使用正确的序数指示符:st
/nd
/rd
/th
后缀?我在文档中没有看到相关提及。
英文:
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.
答案1
得分: 1
标准库中没有支持序数指示符的功能。你可以通过参考这个答案自己实现,或者使用第三方包。
Go语言有一个第三方包可以将输入的整数转换为带有正确序数指示符的字符串,可以查看go-humanize。
此外,如果你查看go-humanize对序数指示符的支持的实现,你会发现它非常简单,所以我建议你可以参考我提供的两个实现自己实现。参考链接:https://github.com/dustin/go-humanize/blob/v1.0.0/ordinals.go#L8
或者,你可以使用go-humanize包。
英文:
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.
答案2
得分: 1
要添加正确的序数指示符(st/nd/rd/th
后缀),你可以使用switch case
语句。我创建了一个示例程序,以打印每个月的所有日期及其相应的后缀,代码如下:
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)
}
}
输出结果:
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th
26th
27th
28th
29th
30th
31st
这段代码会打印出每个日期及其相应的后缀。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论