Hello everyone in advance, thank you very much for your answers and comments. I want to achieve the following I have a date which I get from the database with the following format this date is a string and I store it in the date variable:
date := "2015-02-01T00:00:00Z"
I want to transform said date to the date data type to extract the year with the YEAR() function, which gives me something like the following:
date := "2015-02-01"
I am trying as follows:
newDate, error := time.Parse("2022-02-01", date)
if error != nil {
fmt.Println(error)
}
println("año", date.Year())
However, this returns a 1 and should return 2015, printing the parse returns this:
parsing time "2022-02-01T00:00:00Z" as "2022-02-01": cannot parse "-02-01T00:00:00Z" as "2"
If I print the date variable after parsing, I see that it returns this:
0001-01-01 00:00:00 +0000 UTC
I think what is generating the error are the seconds, minutes and hours in my string but I don't know how to solve it.
I share link to Go Playground: Go playground
The solution to my question is the following:
Since we have a string with the following format
The first thing we have to do is remove "T00:00:00Z", we achieve that with the following code
Up to this point our variable is still a string if we want to have access to the functions of the time package, we have to parse the string to a date
And with this we already have access to methods of the time package for example:
It is not necessary to do that manual trim, you can simply specify the format to the method
Parse()
in your case it would beRFC3339
, I leave you an example:you can see all the supported formats in the Go documentation.