Home >Backend Development >Golang >How to Correctly Parse Tar-like Timestamps in Go's `time.Parse` Function?

How to Correctly Parse Tar-like Timestamps in Go's `time.Parse` Function?

DDD
DDDOriginal
2024-12-09 07:32:06730browse

How to Correctly Parse Tar-like Timestamps in Go's `time.Parse` Function?

Date Parsing in Go

Parsing timestamps in Go can be a daunting task with the intricate API of time.Parse. Let's delve into a common issue encountered when attempting to parse timestamps similar to the ones produced by tar, such as '2011-01-19 22:15'.

Parsing Issue

The following code snippet fails with the error "parsing time "2011-01-19 22:15": month out of range":

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)
}

Understanding the Error

The error message indicates that the format string provided to time.Parse is expecting the month value to be between 1 and 12, while the provided timestamp contains January (represented by 01), which is the first month.

Addressing the Issue

To resolve this issue, we need to customize the format string to correctly interpret the timestamp. Referring to the documentation of the Go time package, we find the following instructions:

"The standard time used in the layouts is:

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

To define your own format, write down what the standard time would look like formatted your way."

Modifying the format string accordingly, we have:

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(t)
}

This code will output: "2011-01-19 22:15:00 0000 UTC".

By following the guidelines provided in the documentation, we were able to customize the format string to successfully parse the timestamp in the desired format.

The above is the detailed content of How to Correctly Parse Tar-like Timestamps in Go's `time.Parse` Function?. 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