Home > Backend Development > Golang > How to Correctly Parse a Timestamp in Go's `time.Parse` Function?

How to Correctly Parse a Timestamp in Go's `time.Parse` Function?

Linda Hamilton
Release: 2024-12-11 07:44:13
Original
302 people have browsed it

How to Correctly Parse a Timestamp in Go's `time.Parse` Function?

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)
}
Copy after login

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:

  • Mon, Jan, 2, 15, 04, 05 are the corresponding values for Month, Day, Day of Month, Hour, Minute, and Second
  • MST is the timezone offset
  • 2006 is the year

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()))
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template