How to convert time.Now() object to string and vice versa in Golang?

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

How to convert time.Now() object to string and vice versa in Golang?

问题

将time.Now()转换为字符串很简单,只需使用time.Now().String()。
如何进行相反的操作呢?

例如,如果time.Now().String()的结果是"2009-11-10 23:00:00 +0000 UTC m=+0.000000001",如何将该字符串转换为time.Time()对象?

英文:

converting time.Now() to string is easy just do time.Now().String().
How to do the reverse part??

ex if time.Now.String() is "2009-11-10 23:00:00 +0000 UTC m=+0.000000001", how to convert this string to time.Time() object

答案1

得分: 1

你正在寻找类似以下的内容,但是layoutstr的值需要修改以正确反映你使用的格式。

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)

layout的值告诉Golang日期的格式应该是什么样的,而str是你的日期值"2009-11-10 23:00:00 +0000 UTC m=+0.000000001"。

英文:

You're looking for something along these lines, but the layout and str values will need to be modified to properly reflect the format you're using.

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)

The layout value tells Golang what the format of the date is expected to be, whereas str is your date value "2009-11-10 23:00:00 +0000 UTC m=+0.000000001"

huangapple
  • 本文由 发表于 2021年8月17日 17:55:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/68815290.html
匿名

发表评论

匿名网友

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

确定