日期格式显示错误的日期

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

Date Format shows wrong date

问题

我正在尝试按照以下格式格式化日期:[daynumber] [monthname] [fullyear]

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    fmt.Println(t.Format("1 January 2014"))
}

然而,这段代码输出的结果是"11 November 10110",而不是正确的日期"29 November 2014"。

请问如何正确使用Time.Format函数?

英文:

I'm trying to format a date like this: [daynumber] [monthname] [fullyear]

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    fmt.Println(t.Format("1 January 2014"))
}

However this prints out "11 November 10110" instead of the correct date "29 November 2014".

What is the correct way to use Time.Format?

答案1

得分: 1

尝试一下:

fmt.Println(t.Format("2006年1月2日"))

来自Time.Format()

> Format根据布局返回时间值的文本表示形式,布局通过显示参考时间的格式来定义,

2006年1月2日 星期一 15:04:05 -0700 MST

文章“在Go中解析和格式化日期/时间”补充说:

> 我认为使用助记符而不是晦涩的格式化代码反映了Go开发人员的实用主义以及他们专注于创建一种使用户更加高效的语言。

讽刺的是,我经常忘记这个格式模板的确切值和顺序。
(特别是日期和月份,我经常混淆,习惯了dd-mm的约定,而不是mm-dd)。

英文:

Try:

fmt.Println(t.Format("2 January 2006"))

From Time.Format()

> Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,

Mon Jan 2 15:04:05 -0700 MST 2006

The article "Parsing and formatting date/time in Go " adds:

> The use of a mnemonic over obscure formatting codes I think reflects the pragmatism of Go’s developers and their focus on creating a language that makes its users more productive

Ironically, I have trouble remembering the exact values and order of that format template.
(Especially the day and month that I keep mixing up, being used to the dd-mm convention, as opposed to mm-dd).

huangapple
  • 本文由 发表于 2014年11月30日 05:16:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/27207215.html
匿名

发表评论

匿名网友

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

确定