Last active
December 24, 2015 09:59
-
-
Save akhenakh/6780857 to your computer and use it in GitHub Desktop.
Json Un/Marshaling Time in UNIX epoch time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"strconv" | |
"time" | |
) | |
type jsonTime time.Time | |
type MyStruct struct { | |
Date jsonTime | |
} | |
func (t jsonTime) MarshalJSON() ([]byte, error) { | |
return []byte(strconv.FormatInt(time.Time(t).Unix(), 10)), nil | |
} | |
func (t *jsonTime) UnmarshalJSON(s []byte) (err error) { | |
q, err := strconv.ParseInt(string(s), 10, 64) | |
if err != nil { | |
return err | |
} | |
*(*time.Time)(t) = time.Unix(q, 0) | |
return | |
} | |
func (t jsonTime) String() string { return time.Time(t).String() } | |
func main() { | |
s := MyStruct{Date:jsonTime(time.Now())} | |
fmt.Println(s.Date) | |
js, err := json.Marshal(s) | |
fmt.Println(string(js), err) | |
b := []byte(`{"Date": 1257894001}`) | |
var m MyStruct | |
err = json.Unmarshal(b, &m) | |
fmt.Println(m.Date, err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment