Golang time.Time.MarshalBinary() and UnmarshalBinary() functions example

package time

Golang time.Time.MarshalBinary() and UnmarshalBinary() functions usage example.

 package main

 import (
 "fmt"
 "time"
 )

 func main() {

 loc, _ := time.LoadLocation("America/New_York")
 t := time.Date(2015, 8, 7, 0, 0, 0, 0, loc)

 fmt.Println("Time : ", t)
 fmt.Println("Time Location : ", t.Location())

 byteTime, err := t.MarshalBinary()

 if err != nil {
 fmt.Println(err)
 }

 fmt.Println("Binary Marshaler encoded : ", byteTime)

 var unByteTime time.Time

 err = unByteTime.UnmarshalBinary(byteTime)

 if err != nil {
 fmt.Println(err)
 }

 fmt.Println("Binary UnMarshaler time : ", unByteTime)

 fmt.Println("Binary UnMarshaler location(missing!) : ", unByteTime.Location())

 // because location is a pointer type (see http://golang.org/pkg/time/#Time.Location)
 // it won't be encoded by Gob
 // but you can translate it back to local time

 fmt.Println("Binary unmarshalled local : ", unByteTime.Local().String())

 // and convert back to target location
 NYTime := unByteTime.In(loc)

 fmt.Println("Binary unmarshalled back to NY time : ", NYTime)

 }

Output :

Time : 2015-08-07 00:00:00 -0400 EDT

Time Location : America/New_York

Binary Marshaler encoded : [1 0 0 0 14 205 86 36 64 0 0 0 0 255 16]

Binary UnMarshaler time : 2015-08-07 00:00:00 -0400 -0400

Binary UnMarshaler location(missing!) :

Binary unmarshalled local : 2015-08-07 12:00:00 +0800 MYT

Binary unmarshalled back to NY time : 2015-08-07 00:00:00 -0400 EDT

References :

http://golang.org/pkg/time/#Time.MarshalBinary

http://golang.org/pkg/time/#Time.UnmarshalBinary

Advertisement