unix.go 780 B

1234567891011121314151617181920212223242526272829303132
  1. package encodedTime
  2. import (
  3. "strconv"
  4. "time"
  5. )
  6. // Unix converts unix times to time.Time
  7. type Unix time.Time
  8. // NewUnix returns a Unix instance with secs since unix-0
  9. func NewUnix(secs int64) Unix {
  10. return Unix(time.Unix(secs, 0))
  11. }
  12. // UnmarshalJSON for Unix converts the []byte value to int64 seconds and than constructs the time with time.Unix()
  13. func (t *Unix) UnmarshalJSON(in []byte) (err error) {
  14. secs, err := strconv.ParseInt(string(in), 10, 64)
  15. if err != nil {
  16. return err
  17. }
  18. *t = Unix(time.Unix(secs, 0))
  19. return nil
  20. }
  21. // MarshalJSON takes the Unix() seconds from the time and uses strconv.FormatInt() to return the string of digits
  22. func (t Unix) MarshalJSON() ([]byte, error) {
  23. secs := time.Time(t).Unix()
  24. return []byte(strconv.FormatInt(secs, 10)), nil
  25. }