Home >Backend Development >Golang >How to Correctly Convert a Unix Timestamp to a Go time.Time Object?

How to Correctly Convert a Unix Timestamp to a Go time.Time Object?

DDD
DDDOriginal
2024-12-17 05:48:25972browse

How to Correctly Convert a Unix Timestamp to a Go time.Time Object?

Unix Timestamp to Time.Time Conversion - Addressing Out of Range Error

When parsing Unix timestamps using time.Parse(), you may encounter an "out of range" error even with the correct date and time format. This is because time.Parse() is not intended for Unix timestamp parsing.

To resolve this, use the following steps:

  1. Parse the Unix timestamp as an int64: Use strconv.ParseInt() to convert the timestamp string to an integer in base 10 (or any other base you prefer).
  2. Convert the int64 to a time.Time: Create a time.Time object using time.Unix(i, 0), where 'i' is the parsed int64 from step 1. This will generate a Time object with the correct date and time corresponding to the Unix timestamp.

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

Output:

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

This method ensures that Unix timestamps are correctly parsed and converted to time.Time objects, avoiding the out of range error.

The above is the detailed content of How to Correctly Convert a Unix Timestamp to a Go time.Time Object?. 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