-1

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?

MenyT
  • 1,653
  • 1
  • 8
  • 19
supriya
  • 37
  • 1
  • 5
  • 2
    You're ignoring the error returned by `time.Parse`. Don't ignore errors. – colm.anseo Oct 07 '21 at 21:12
  • 1
    Just to note re. "I am using go 14.4" - I assume you mean 1.14.4, which puts you about two years out of date. You should definitely consider upgrading for current security and performance fixes. – Adrian Oct 07 '21 at 21:28

1 Answers1

3

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.

colm.anseo
  • 19,337
  • 4
  • 43
  • 52