英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论