doushanmo7024 2015-03-05 23:27
浏览 79
已采纳

在Go中格式化详细日期

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?

  • 写回答

1条回答 默认 最新

  • doucheng9634 2015-03-06 00:54
    关注

    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")
    }
    

    <kbd>play</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP