golang struct convert unix timestamp to date string¶
Let's quickly check how we can convert unix timestamp to date string in a Go language. You may already used the unix timestamp, but let's quickly go through what is a unix timestamp ? the Unix timestamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC.
Convert unix timestamp or Epoch to date string¶
Lets do a simple code that can convert the unix epoch to date string.
package main
import "fmt"
import "time"
func main() {
var unixTime int64 = 1573142098
t := time.Unix(unixTime, 0)
strDate := t.Format(time.UnixDate)
fmt.Println(strDate)
}
// output: Thu Nov 7 15:54:58 UTC 2019
Create Epoch type to use in a Struct¶
Let's create a type "Epoch" and bind the methods "MarshalJSON" that converts the epoch time to a date string. Let's bind another method "UnmarshalJSON" that converts a date string(i.e bytes array) to epoch time. These two methods will be used when we use json decoding and encoding.
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type Epoch int64
func (t Epoch) MarshalJSON() ([]byte, error) {
strDate := time.Time(time.Unix(int64(t), 0)).Format(time.RFC3339)
out := []byte(`"` + strDate + `"`)
return out, nil
}
func (t *Epoch) UnmarshalJSON(b []byte) (err error) {
s := strings.Trim(string(b), "\"")
q, err := time.Parse(time.RFC3339, s)
if err != nil {
return err
}
*t = Epoch(q.Unix())
return nil
}
type MyStruct struct {
Date Epoch
}
func main() {
s := MyStruct{Date: Epoch(1980342000)}
fmt.Println(s.Date)
js, err := json.Marshal(s)
fmt.Println(string(js), err)
b := []byte(`{"date": "2032-10-02T15:00:00Z"}`)
var m MyStruct
err = json.Unmarshal(b, &m)
fmt.Println(m.Date, err)
}
// OUTPUT:
// 1980342000
// {"Date":"2032-10-02T15:00:00Z"}
// 1980342000
References: