Serializing the time and date
When serializing the date and time information, it is necessary to choose the proper format. This recipe will illustrate how the time
package helps to choose one and do the serialization properly.
How to do it...
- Open the console and create the folder
chapter04/recipe12
. - Navigate to the directory.
- Create the
serialize.go
file with the following content:
package main import ( "encoding/json" "fmt" "time" ) func main() { eur, err := time.LoadLocation("Europe/Vienna") if err != nil { panic(err) } t := time.Date(2017, 11, 20, 11, 20, 10, 0, eur) // json.Marshaler interface b, err := t.MarshalJSON() if err != nil { panic(err) } fmt.Println("Serialized as RFC 3339:", string(b)) t2 := time.Time{} t2.UnmarshalJSON(b) fmt.Println("Deserialized from RFC 3339:", t2)...