Home >Backend Development >Golang >How to Correctly Parse Non-Standard Dates and Times in Go?

How to Correctly Parse Non-Standard Dates and Times in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 09:28:05327browse

How to Correctly Parse Non-Standard Dates and Times in Go?

Parsing Dates 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:

  • Mon Jan 2 15:04:05 MST 2006 (MST is GMT-0700)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn