How to Parse Unix Timestamp to time.Time

To parse a UNIX timestamp to time.Time, you can use the strconv.ParseInt() function to convert a string to int64 and create a timestamp with time.Unix() function.

package main

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

func main() {
  unixTimestamp, err := strconv.ParseInt("1677638510", 10, 64)
  if err != nil {
    panic(err)
  }
  t := time.Unix(unixTimestamp, 0)

  fmt.Printf("Unix timestamp %d corresponds to the time: %v\n", unixTimestamp, t)
}

Output

Unix timestamp 1677638510 corresponds to the time: 2023-03-01 08:11:50 +0530 IST

In this code example, we converted a Unix timestamp string “1677638510” to an int64 value using the strconv.ParseInt() function and then convert the Unix timestamp to a time.Time value using time.Unix() function.

If you have a Unix timestamp in milliseconds, you must convert it to seconds and nanoseconds before passing it to time.Unix() function.

unixTimestampMillis := int64(1677638510000)
seconds := unixTimestampMillis / 1000
nanoseconds := (unixTimestampMillis % 1000) * 1000000
t := time.Unix(seconds, nanoseconds)

That’s it.

Leave a Comment