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.
</div>
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.