使用Go语言时的时间格式问题

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

Time format issue with go language

问题

我正在使用go 14.4版本,并在转换时间时遇到一个特定的问题。所以我需要将当前时间转换为2006-01-02T15:04:05Z格式,并使用以下代码:

currentTime := time.Now().Format(time.RFC3339)
currentDateTime, _ := time.Parse("2006-01-02T15:04:05Z", currentTime)

但是运行时输出为"0001-01-01 00:00:00 +0000 UTC",在go playground中运行时输出为"2009-11-10 23:00:00 +0000 UTC"。

有什么办法可以解决这个问题吗?

英文:

I am using go 14.4 version and seeing a particular issue when converting time. So I need current time to be converted to this format 2006-01-02T15:04:05Z and using below code

currentTime := time.Now().Format(time.RFC3339)
currentDateTime, _ := time.Parse("2006-01-02T15:04:05Z", currentTime)

But getting output as "0001-01-01 00:00:00 +0000 UTC"
when running same in go playground getting output as "2009-11-10 23:00:00 +0000 UTC"

Any idea on how to fix this?

答案1

得分: 3

首先,不要忽略错误 - 这就是为什么你得到了一个“零”时间的原因,因为时间字符串没有被正确解析。

由于你正在使用 RFC3339 格式化时间字符串:

currentTime := time.Now().Format(time.RFC3339)

只需使用相同的格式 time.RFC3339 进行解析:

//currentDateTime, err := time.Parse("2006-01-02T15:04:05Z", currentTime) // wrong format
currentDateTime, err := time.Parse(time.RFC3339, currentTime)

if err != nil {
	// 处理错误
}

FYI 这是 time 包的格式字符串列表。

英文:

Firstly don't ignore errors - that is why you are getting a "zero" time - because the time string was not parsed correctly.

Since you are using RFC3339 to format the time string:

currentTime := time.Now().Format(time.RFC3339)

simply use the same format time.RFC3339 to parse it back:

//currentDateTime, err := time.Parse("2006-01-02T15:04:05Z", currentTime) // wrong format
currentDateTime, err := time.Parse(time.RFC3339, currentTime)

if err != nil {
	// handle error
}

FYI heres a list of the time package's format strings.

huangapple
  • 本文由 发表于 2021年10月8日 05:06:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/69487860.html
匿名

发表评论

匿名网友

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

确定