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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程