在Go语言中格式化详细日期

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

Formatting Verbose Dates in Go

问题

我想要以人类可读的格式生成格式化日期。通常在英语环境中,日期的后缀会用于表示月份的天数,例如1st、2nd、3rd、4th、5th等等。

我尝试使用格式字符串"Monday 2nd January"来格式化这样的日期,但似乎不起作用。

例如,在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))
}

这将生成结果:

Wednesday 4nd March
Sunday 1nd March

但我期望的结果是:

Wednesday 4th March
Sunday 1st March

我做错了什么?

英文:

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

得分: 6

这种格式不支持,你需要自己实现,可以像这样使用一个(hacky)的方法:

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](http://play.golang.org/p/9szb7X1mum)[/kbd]
英文:

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>

huangapple
  • 本文由 发表于 2015年3月6日 07:27:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/28889818.html
匿名

发表评论

匿名网友

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

确定