Golang time.Time.MarshalJSON() and UnmarshalJSON() functions example
package time
Golang time.Time.MarshalJSON() and UnmarshalJSON() 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.MarshalJSON()
if err != nil {
fmt.Println(err)
}
fmt.Println("JSON Marshaler raw byte : ", byteTime)
fmt.Println("JSON Marshaler byte in string : ", string(byteTime))
var unByteTime time.Time
err = unByteTime.UnmarshalJSON(byteTime)
if err != nil {
fmt.Println(err)
}
fmt.Println("JSON UnMarshaler time : ", unByteTime)
fmt.Println("JSON UnMarshaler location(missing!) : ", unByteTime.Location())
// because location is a pointer type (see http://golang.org/pkg/time/#Time.Location)
// it won't be encoded
// but you can translate it back to local time
fmt.Println("JSON unmarshaled local : ", unByteTime.Local().String())
// and convert back to target location
NYTime := unByteTime.In(loc)
fmt.Println("JSON unmarshaled back to NY time : ", NYTime)
}
Output :
Time : 2015-08-07 00:00:00 -0400 EDT
Time Location : America/New_York
JSON Marshaler raw byte : [34 50 48 49 53 45 48 56 45 48 55 84 48 48 58 48 48 58 48 48 45 48 52 58 48 48 34]
JSON Marshaler byte in string : "2015-08-07T00:00:00-04:00"
JSON UnMarshaler time : 2015-08-07 00:00:00 -0400 -0400
JSON UnMarshaler location(missing!) :
JSON unmarshaled local : 2015-08-07 12:00:00 +0800 MYT
JSON unmarshaled back to NY time : 2015-08-07 00:00:00 -0400 EDT
References :
Advertisement
Something interesting
Tutorials
+5.8k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+51.1k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+10k Golang : Convert octal value to string to deal with leading zero problem
+6.2k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+17.4k Golang : Check if IP address is version 4 or 6
+6.3k Golang : How to get capacity of a slice or array?
+13.4k Golang : Verify token from Google Authenticator App
+6.2k Golang : Extract XML attribute data with attr field tag example
+21.5k Golang : How to read float value from standard input ?
+5.4k Python : Delay with time.sleep() function example
+15.6k Golang : How to convert(cast) IP address to string?
+22.1k Golang : Print leading(padding) zero or spaces in fmt.Printf?