Home >Backend Development >Golang >How to Correctly Parse Non-Standard Dates and Times in Go?
When working with timestamps, it's common to encounter formats other than the standard Unix epoch timestamp. For instance, tar produces timestamps in the format 2011-01-19 22:15. To parse such timestamps in Go, we turn to the time.Parse function.
However, simply calling time.Parse("2011-01-19 22:15", "2011-01-19 22:15") will result in an error: "parsing time 2011-01-19 22:15: month out of range". To understand why, we need to delve into the time.Parse function's unconventional API.
The Formatting String Quirks
The time.Parse function requires a formatting string that specifies how to interpret the input timestamp. For our purposes, let's use the 2006-01-02 15:04 format. This string follows the conventions laid out in the Go time package documentation:
To define our own format, we simply need to specify how the elements of the standard format would appear in our custom format. For instance, in our case, the resulting format would be 2006-01-02 15:04.
Parsing the Timestamp
With our formatting string in place, we can now parse the timestamp:
This will correctly parse the timestamp and display the resulting time.Time object.
The above is the detailed content of How to Correctly Parse Non-Standard Dates and Times in Go?. For more information, please follow other related articles on the PHP Chinese website!