-2

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.

JimB
  • 104,193
  • 13
  • 262
  • 255
Priyanka
  • 354
  • 7
  • 14
  • 1
    It's still a duplicate, because other questions and answers have the exact same problem and give the correct solution, just not necessarily for your exact time format. We shouldn't need a new question for every possible time format - simple information on how to use parse formats should be sufficient. – Adrian Nov 17 '17 at 15:31

1 Answers1

9

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.

icza
  • 389,944
  • 63
  • 907
  • 827