Skip to content

Instantly share code, notes, and snippets.

@akhenakh
Last active December 24, 2015 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akhenakh/6780857 to your computer and use it in GitHub Desktop.
Save akhenakh/6780857 to your computer and use it in GitHub Desktop.
Json Un/Marshaling Time in UNIX epoch time
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