Home > Backend Development > Golang > How to Safely Parse Unix Timestamps in Go?

How to Safely Parse Unix Timestamps in Go?

Mary-Kate Olsen
Release: 2024-12-17 00:49:25
Original
297 people have browsed it

How to Safely Parse Unix Timestamps in Go?

How to Parse Unix Timestamps

Parsing Unix timestamps in Go may seem like a simple task, but it can lead to unexpected errors. When attempting to parse a timestamp using time.Parse, you may encounter an out of range error even if the layout appears to be correct.

The reason for this is that time.Parse does not handle Unix timestamps. Instead, you should use the strconv.ParseInt function to convert the timestamp string to an int64 and then use the time.Unix function to create a time.Time object.

Here's an example:

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

This code will output the correct timestamp:

2014-07-16 20:55:46 +0000 UTC
Copy after login

Important Note:

In the original example, strconv.Atoi was used instead of strconv.ParseInt. However, strconv.Atoi can result in integer overflows on 32-bit systems. Therefore, strconv.ParseInt is recommended to handle all cases safely.

The above is the detailed content of How to Safely Parse Unix 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