将字符串转换为时间并在Golang中解析。

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

convert string to time and parse in golang

问题

我正在从文件中读取一个时间戳,并将其赋值给t

t := "2016-11-02 19:23:05.503705739 +0000 UTC"

当我尝试解析这个字符串时:

time, err := time.Parse("2016-11-02 19:18:57.149197306 +0000 UTC", t)

结果是:

0001-01-01 00:00:00 +0000 UTC

但我期望的结果是:

"2016-11-02 19:18:57.149197306 +0000 UTC"

请给予建议。

英文:

I'm reading a timestamp from a file, and I assign the value to t:

t := "2016-11-02 19:23:05.503705739 +0000 UTC"

When I attempt to parse the string:

time, err := time.Parse("2016-11-02 19:18:57.149197306 +0000 UTC", t)

The result is:

0001-01-01 00:00:00 +0000 UTC

But I expected result to be:

"2016-11-02 19:18:57.149197306 +0000 UTC" ?

Please advise.

答案1

得分: 3

你没有正确提供Parse函数的layout参数。你应该使用Mon Jan 2 15:04:05 MST 2006(这是一个特殊值,你可以创建一个符合你要求格式的字符串,但日期要使用这个值)作为给定格式的基准。在你的情况下,应该是2006-01-02 15:04:05.000000000 +0000 UTC,再加上我暂时不知道的MST时区的偏移量。

英文:

You're not correctly providing the layout argument to Parse. You're supposed to be using Mon Jan 2 15:04:05 MST 2006 (this is magic value, you put create a string in the format you want but with that date) in the given format so in your case, it would be 2006-01-02 15:04:05.000000000 +0000 UTC plus the offset which I don't know off the top of my head for MST.

huangapple
  • 本文由 发表于 2016年11月3日 03:31:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/40388246.html
匿名

发表评论

匿名网友

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

确定