Localization when using time.Format

huangapple go评论82阅读模式
英文:

Localization when using time.Format

问题

time包中,当格式化一个time.Time变量时,输出将使用未导出的[]string切片中定义的英文星期和月份名称。

如何本地化字符串,使用不同的语言(希望仍然使用Format())?

示例:

fmt.Println(time.Now().Format("Mon 2 January 2006"))

输出:

>Tue 28 January 2014

期望的输出:

>Tis 28 Januari 2014

Playground

英文:

In the time package, when formatting a time.Time variable, the output will use the English names for weeks and months as defined in unexported []string slices.

How to localize the string, using a different language (hopefully still using Format())?

Example:

fmt.Println(time.Now().Format("Mon 2 January 2006"))

Output:

>Tue 28 January 2014

Desired output:

>Tis 28 Januari 2014

Playground

答案1

得分: 8

如您在时间包的源代码中所见,值是硬编码在源代码中的。所以,基本上,Go语言目前不支持国际化(i18n)。国际化在Go语言的路线图上,甚至在常见问题解答中也有提到,但最近对这个主题没有任何评论。

与此同时,您可以尝试使用Monday包:

// 将LocaleEnUS更改为您想要用于翻译的区域设置
monday.Format(time.Now(), "Mon 2 January 2006", monday.LocaleEnUS)

英文:

As you can see in time package sourcecode that values are hardcoded in source. So, basically, Go doesn't support i18n right now. i18n is on Go roadmap, its even mentioned in the faq, but there were no comments on that topic recently.

Meanwhile, you could try to use Monday package:

  // Change LocaleEnUS to the locale you want to use for translation
  monday.Format(time.Now(), "Mon 2 January 2006", monday.LocaleEnUS) 

huangapple
  • 本文由 发表于 2014年1月28日 16:12:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/21400121.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定