-1

When I try to run the following statement:

eolTime, tErr := time.Parse(time.RFC3339, eolDetails.EOL.(string))
// eolDetails.EOL.(string) evaluates to 2021-04-30

I get an error saying error evaluating "time.RFC3339" as argument layout in function time.Parse: could not find symbol value for time" (unused functions are not included into executable)"

What does this error mean? What do I need to do parse the date into go date?

Here is also the screenshot while debugging that shows the error: enter image description here

It is strange, that it works fine on the playground. Any idea what could be wrong here?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

1 Answers1

3

Go version 1.20+

Go version 1.20 adds three new layout constants: DateTime, DateOnly, and TimeOnly (release notes). So, if the string you want to parse contains only a date you can use the DateOnly layout.

eolDetails := "2021-04-30"
eolTime, tErr := time.Parse(time.DateOnly, eolDetails)
if tErr != nil {
    panic(err)
}
fmt.Println(eolTime)

https://go.dev/play/p/qrBiETSmRrs


Go version 1.19 and older

If you are using a version that is older than 1.20, then you can use a custom layout. When using custom layouts you only need to make sure that they are a valid reference time, as explained by the package's documentation:

To define your own format, write down what the reference time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples. The model is to demonstrate what the reference time looks like so that the Format and Parse methods can apply the same transformation to a general time value.

Where the "reference time" is defined as:

... The reference time used in these layouts is the specific time stamp:

01/02 03:04:05PM '06 -0700

So to parse your date string you can simply do the following:

eolLayout := "2006-01-02"
eolDetails := "2021-04-30"
eolTime, tErr := time.Parse(eolLayout, eolDetails)
if tErr != nil {
    panic(tErr)
}
fmt.Println(eolTime)

https://go.dev/play/p/-6SqMz94VMT?v=goprev


Related StackOverflow posts:

mkopriva
  • 35,176
  • 4
  • 57
  • 71