Date Parsing in Go
While attempting to parse a timestamp in the format '2011-01-19 22:15', which is commonly used by tar, developers may encounter difficulties using the time.Parse function. This article seeks to provide a solution to this issue.
The following code snippet demonstrates the unsuccessful attempt to parse the timestamp using time.Parse:
package main import ( "fmt" "time" ) func main() { var time, error = time.Parse("2011-01-19 22:15", "2011-01-19 22:15") if error != nil { fmt.Println(error.String()) return } fmt.Println(time) }
This code fails with the error message "'parsing time "2011-01-19 22:15": month out of range'".
The solution lies in understanding the syntax and semantics of time.Parse. As specified in the Go time package documentation, the default layout used in time.Parse is based on the standard Unix time format:
"Mon Jan 2 15:04:05 MST 2006 (MST is GMT-0700)"
where:
To define a custom layout, developers need to determine how the standard time would appear in their desired format. For example, to parse the '2011-01-19 22:15' timestamp, the following snippet can be used:
package main import ( "fmt" "time" ) func main() { t, err := time.Parse("2006-01-02 15:04", "2011-01-19 22:15") if err != nil { fmt.Println(err) return } fmt.Println(time.SecondsToUTC(t.Seconds())) }
Here, we have specified a custom layout string "2006-01-02 15:04" to match the input timestamp. The result is then printed in Unix time format.
The above is the detailed content of How to Correctly Parse a Timestamp in Go's `time.Parse` Function?. For more information, please follow other related articles on the PHP Chinese website!