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
References :
http://golang.org/pkg/time/#Time.GobDecode
Advertisement
Something interesting
Tutorials
+14k Golang : convert rune to unicode hexadecimal value and back to rune character
+8.6k Golang : Progress bar with ∎ character
+14.6k Golang : GUI with Qt and OpenCV to capture image from camera
+7.4k Golang : Example of custom handler for Gorilla's Path usage.
+18.5k Golang : Aligning strings to right, left and center with fill example
+39.6k Golang : Remove dashes(or any character) from string
+8.4k Golang : Ackermann function example
+17.6k Golang : Parse date string and convert to dd-mm-yyyy format
+8.9k Golang : Gaussian blur on image and camera video feed examples
+31.6k Golang : Get local IP and MAC address
+5.4k Golang : Get S3 or CloudFront object or file information
+7.8k Golang : Lock executable to a specific machine with unique hash of the machine