Golang : time.Time.GobEncode(), GobDecode() and In() functions example

** package time**

Golang : time.Time.GobEncode() and GobDecode() functions usage example.

NOTE : When you use GobEncode, information such as location will NOT be serialize(marshal) into byte, because Location type is a pointer. See the code below for missing location part. Fortunately, you can use the time.Time.In() function to translate back to original Location time

 package main

 import (
 "fmt"
 "time"
 )

 func main() {

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

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

 gobEncoded, err := t.GobEncode()

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

 fmt.Println("Gob encoded : ", gobEncoded)

 // with GOB encoded(marshalled) data, can save to file(serialize)

 // now, pretend that we loaded the GOB data
 // we want to decode(unmarshal) the data

 var gobTime time.Time

 err = gobTime.GobDecode(gobEncoded)

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

 fmt.Println("Gob decoded time : ", gobTime)

 fmt.Println("Gob decoded location(missing!) : ", gobTime.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("Gob decoded local : ", gobTime.Local().String())

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

 fmt.Println("Gob decoded back to NY time : ", NYTime)

 }

Output :

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

Time Location : America/New_York

Gob encoded : [1 0 0 0 14 205 84 210 192 0 0 0 0 255 16]

Gob decoded time : 2015-08-06 00:00:00 -0400 -0400

Gob decoded location(missing!) :

Gob decoded local : 2015-08-06 12:00:00 +0800 MYT

Gob decoded back to NY time : 2015-08-06 00:00:00 -0400 EDT

SEE ALSO : https://www.socketloop.com/tutorials/golang-get-local-time-and-equivalent-time-in-different-time-zone

References :

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

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

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

Advertisement