Parse string as a time.Time value [duplicate]

2019-09-22 07:56发布

This question already has an answer here:

I have a string time in format 20171023T183552. I didn't find any format to parse this string value. Is there any way to convert this string value to Go time.Time ?

Edit - This is not duplicate question. I know how to parse, but I was unaware of the fact that we can use any layout other than listed in time format package. This answer cleared my daubt.

标签: parsing go time
1条回答
贼婆χ
2楼-- · 2019-09-22 08:25

That is simply "YYYYMMDDTHHmmSS", so use the format string (layout): "20060102T150405".

Example:

s := "20171023T183552"
t, err := time.Parse("20060102T150405", s)
fmt.Println(t, err)

Output (try it on the Go Playground):

2017-10-23 18:35:52 +0000 UTC <nil>

Quoting from doc of time.Parse():

Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be

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

would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

So basically generate the format string by formatting the reference time using the same format your input is available in.

For the opposite direction (converting time.Time to string), see Golang: convert time.Time to string.

查看更多
登录 后发表回答