Golang time.Time.MarshalText() and UnmarshalText() functions example
package time
Golang time.Time.MarshalText() and UnmarshalText() 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.MarshalText()
if err != nil {
fmt.Println(err)
}
fmt.Println("MarshalText raw byte : ", byteTime)
fmt.Println("MarshalText byte in string : ", string(byteTime))
var unByteTime time.Time
err = unByteTime.UnmarshalText(byteTime)
if err != nil {
fmt.Println(err)
}
fmt.Println("UnmarshalText time : ", unByteTime)
fmt.Println("UnmarshalText 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("UnmarshalText local : ", unByteTime.Local().String())
// and convert back to target location
NYTime := unByteTime.In(loc)
fmt.Println("UnmarshalText-ed back to NY time : ", NYTime)
}
Output :
Time : 2015-08-07 00:00:00 -0400 EDT
Time Location : America/New_York
MarshalText raw byte : [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]
MarshalText byte in string : 2015-08-07T00:00:00-04:00
UnmarshalText time : 2015-08-07 00:00:00 -0400 -0400
UnmarshalText location(missing!) :
UnmarshalText local : 2015-08-07 12:00:00 +0800 MYT
UnmarshalText-ed back to NY time : 2015-08-07 00:00:00 -0400 EDT
References :
Advertisement
Something interesting
Tutorials
+15.3k Golang : Delete certain files in a directory
+22k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+9.3k Golang : How to get garbage collection data?
+5.9k Golang : Extract unicode string from another unicode string example
+9.4k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+15.4k Golang : Find location by IP address and display with Google Map
+11.5k Golang : Generate DSA private, public key and PEM files example
+22.2k Golang : Convert seconds to minutes and remainder seconds
+9.1k Golang : Intercept and compare HTTP response code example
+3.7k Golang : Switch Redis database redis.NewClient
+5.3k Python : Convert(cast) string to bytes example
+6.9k How to let Facebook Login button redirect to a particular URL ?