I am using go 14.4 version and seeing a particular issue when converting time. So I need current time to be converted to this format 2006-01-02T15:04:05Z
and using below code
currentTime := time.Now().Format(time.RFC3339)
currentDateTime, _ := time.Parse("2006-01-02T15:04:05Z", currentTime)
But getting output as "0001-01-01 00:00:00 0000 UTC" when running same in go playground getting output as "2009-11-10 23:00:00 0000 UTC"
Any idea on how to fix this?
CodePudding user response:
Firstly don't ignore errors - that is why you are getting a "zero" time - because the time string was not parsed correctly.
Since you are using RFC3339
to format the time string:
currentTime := time.Now().Format(time.RFC3339)
simply use the same format time.RFC3339
to parse it back:
//currentDateTime, err := time.Parse("2006-01-02T15:04:05Z", currentTime) // wrong format
currentDateTime, err := time.Parse(time.RFC3339, currentTime)
if err != nil {
// handle error
}
FYI heres a list of the time
package's format strings.