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: