dongxiansi0158 2017-01-27 15:18
浏览 135
已采纳

如何使用语言环境将日期转换为字符串?

I convert date to a string this way:

d.Format("Mon 02. Jan")

and I get something like

Fri 27. Jan

How can I switch the locale and get the string in other language?

  • 写回答

1条回答 默认 最新

  • doubi5127 2017-01-27 15:30
    关注

    You can't. The Go standard library does not contain localized month, day and zone names. The names are wired into the time package.

    For example, the name of the months returned by Month.String() are stored in the unexported time.month global variable:

    var months = [...]string{
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    }
    
    func (m Month) String() string { return months[m-1] }
    

    Similarly, names of weekdays come from Weekday.String(), stored in unexported variable time.days.

    Having said that, there may be 3rd party libraries supporting your needs. Here's an incomplete one which might be of some help to you: https://github.com/mattbaird/go-i18n-formats

    As shared by Igor Chubin below, this 3rd party lib is much more complete: https://github.com/variadico/lctime

    Also note that while providing a general, multilingual time formatting package is not an easy task, if you really need it, you could take the time package, copy it to your project and just translate the names to the language you need.

    Also note that supporting a low number of languages and low number of layouts, it's easy to create the formatting yourself.

    For example, the code below formats a given time.Time value in Hungarian, using the layout you used in your question:

    func Format(t time.Time) string {
        return fmt.Sprintf("%s %02d. %s",
            days[t.Weekday()][:3], t.Day(), months[t.Month()-1][:3],
        )
    }
    
    var days = [...]string{
        "Vasárnap", "Hétfő", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat"}
    
    var months = [...]string{
        "Január", "Február", "Március", "Április", "Május", "Június",
        "Július", "Augusztus", "Szeptember", "Október", "November", "December",
    }
    

    Testing it:

    fmt.Println(Format(time.Now()))
    

    Output on the Go Playground:

    Ked 10. Nov
    

    Output on my local machine:

    Pén 27. Jan
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值