Skip to content

Instantly share code, notes, and snippets.

@benzsuankularb
Last active December 25, 2016 13:19
Show Gist options
  • Save benzsuankularb/159511922798b8f7e5a0276027f51570 to your computer and use it in GitHub Desktop.
Save benzsuankularb/159511922798b8f7e5a0276027f51570 to your computer and use it in GitHub Desktop.
Timestamp for marshal/unmarshal json from javascript timestamp
package timestamp
import (
"strconv"
"time"
)
// Declare as *Timestamp to get it worked else it will use default time string format.
type Timestamp struct {
time.Time
}
func (t *Timestamp) MarshalJSON() ([]byte, error) {
ts := t.Time.UnixNano() / 1000
return []byte(strconv.Itoa(int(ts))), nil
}
func (t *Timestamp) UnmarshalJSON(b []byte) error {
ts, err := strconv.Atoi(string(b))
if err != nil {
return err
}
ts64 := int64(ts)
t.Time = time.Unix(ts64/int64(time.Millisecond), ts64%int64(time.Millisecond)*1000)
return nil
}
func (t *Timestamp) IsZero() bool {
return t.Second() == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment