Golang: parse and format unix timestamp

If you have unix timestamp in String

Share on:  
                 

alt

1. If you have unix timestamp in String

The time.Parse function does not do Unix timestamps. Instead you can use strconv.ParseIntto parse the string to int64 and create the timestamp with time.Unix:

package main

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

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

2. If you have unix timestamp in int

The time.Parse function does not do Unix timestamps.

package main

import (
    "fmt"
    "time"
)

func main() {

tm := time.Unix(1518328047, 0)
    fmt.Println(tm)
}

3. If you want to convert timestamp to RFC3339

Use time.Format and provide time.RFC3339 format

package main

import (
 "fmt"
 "time"
)

func main() {
 
 unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc 
 
 unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format
 
 fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
 fmt.Println("unix time stamp in unitTimeInRFC3339 format :---->",unitTimeInRFC3339)
}

Reference

  1. https://golang.org/pkg/strconv/
  2. https://golang.org/pkg/time/
Tags:   GOGO LANG