Home >Backend Development >Golang >How Can I Correctly Parse Unix Timestamps in Go?

How Can I Correctly Parse Unix Timestamps in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 21:20:15443browse

How Can I Correctly Parse Unix Timestamps in Go?

Parsing Unix Timestamps in Go

Parsing Unix timestamps in Go may seem straightforward, but it can lead to unexpected errors. This article explores an issue commonly encountered and provides a solution.

Problem Statement

Consider the following code snippet:

package main

import "fmt"
import "time"

func main() {
    tm, err := time.Parse("1136239445", "1405544146")
    if err != nil{
        panic(err)
    }

    fmt.Println(tm)
}

The goal is to convert the Unix timestamp "1405544146" to a time.Time object. However, running this code results in an error:

panic: parsing time "1405544146" as "1136239445": cannot parse "1405544146" as "06:20:23.9445"

Solution

The time.Parse function is designed to parse time strings using a specified layout. In this case, the layout "1136239445" does not match the format of the Unix timestamp. To parse a Unix timestamp, you need to use an integer representation.

Instead of using time.Parse, you can use strconv.ParseInt to parse the string to an int64 and then create the timestamp using time.Unix:

package main

import (
    "fmt"
    "time"
    "strconv"
)

func main() {
    i, err := strconv.ParseInt("1405544146", 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(i, 0)
    fmt.Println(tm)
}

Output:

2014-07-16 20:55:46 +0000 UTC

By using strconv.ParseInt, you can avoid the layout-related errors and successfully parse Unix timestamps.

The above is the detailed content of How Can I Correctly Parse Unix Timestamps 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