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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动