Home >Backend Development >Golang >How to Parse Non-Standard Timestamps like Tar's Output in Go?
Date Parsing in Go
Parsing timestamps in Go can be a challenge, especially when working with non-standard formats. One such scenario involves parsing timestamps generated by tar, such as '2011-01-19 22:15'.
The initial attempt to parse this timestamp using the time.Parse function fails with the error message "parsing time "2011-01-19 22:15": month out of range." This error stems from the fact that the default time format used by time.Parse expects a standard format that differs from the tar timestamp.
To resolve this issue, consult the Go time package documentation for instructions on defining custom date formats. According to the documentation, the standard time format is in the form of "Mon Jan 2 15:04:05 MST 2006". To create a custom format, simply map the elements of the standard format to the corresponding elements in your desired format.
For instance, to parse the tar timestamp "2011-01-19 22:15", use the following code:
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())) }
Output:
Wed Jan 19 22:15:00 UTC 2011
With this custom format, the time.Parse function will correctly parse the tar timestamp and return an equivalent time.Time object in UTC format.
The above is the detailed content of How to Parse Non-Standard Timestamps like Tar's Output in Go?. For more information, please follow other related articles on the PHP Chinese website!