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
Release: 2024-12-17 05:48:25
Original
894 people have browsed it

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

Output:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template