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 :
Advertisement
Something interesting
Tutorials
+11.6k Golang : Concurrency and goroutine example
+24.5k Golang : How to validate URL the right way
+20.9k Golang : Convert PNG transparent background image to JPG or JPEG image
+11.3k Golang : How to flush a channel before the end of program?
+11.2k CodeIgniter : How to check if a session exist in PHP?
+26.8k Golang : Find files by extension
+10.8k Golang : Natural string sorting example
+11.4k Golang : Concatenate (combine) buffer data example
+8.3k Golang : Oanda bot with Telegram and RSI example
+5.9k Golang : Use NLP to get sentences for each paragraph example
+37.5k Golang : Converting a negative number to positive number