Home > Backend Development > Golang > How Can I Parse Non-Standard Timestamps in Go?

How Can I Parse Non-Standard Timestamps in Go?

Barbara Streisand
Release: 2024-12-13 09:57:13
Original
938 people have browsed it

How Can I Parse Non-Standard Timestamps in Go?

Parsing Timestamps in Go

Parsing timestamps from external sources, such as archives created by the tar utility, can be challenging due to the potential for unique formatting. The Go time package provides a variety of functions for parsing timestamps, but its intricate API can lead to confusion.

Parse with a Custom Template

For timestamps in a non-standard format, like "2011-01-19 22:15," it's necessary to use a custom layout template when parsing. Refer to the Go time package documentation for guidance on defining layout templates based on the format of your timestamp.

Example

For the timestamp "2011-01-19 22:15," we would define the layout template as "2006-01-02 15:04," where each component represents the corresponding part of the timestamp. The following code snippet demonstrates this approach:

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) // Output: 2011-01-19 22:15:00 +0000 UTC
}
Copy after login

The above is the detailed content of How Can I Parse Non-Standard Timestamps in Go?. 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