millisecs.go 884 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package encodedTime
  2. import (
  3. "bytes"
  4. "math"
  5. "strconv"
  6. "time"
  7. )
  8. // Millisecs is used to get a time from an js number that represents a timestamp in milliseconds
  9. type Millisecs time.Time
  10. // NewMillisecs returns a Millisecs instance with secs converted to millisecs (*1000)
  11. func NewMillisecs(secs int64) Millisecs {
  12. return Millisecs(time.Unix(secs, 0))
  13. }
  14. func (t *Millisecs) UnmarshalJSON(in []byte) (err error) {
  15. dot := []byte{'.'}
  16. i := bytes.Index(in, dot)
  17. if i == -1 {
  18. i = 1000
  19. } else {
  20. i = int(math.Pow(10, float64(len(in)-i-2)))
  21. in = bytes.Replace(in, dot, []byte{}, 1)
  22. }
  23. secs, err := strconv.ParseInt(string(in), 10, 64)
  24. if err != nil {
  25. return err
  26. }
  27. *t = Millisecs(time.Unix(secs/int64(i), 0))
  28. return nil
  29. }
  30. func (t Millisecs) MarshalJSON() ([]byte, error) {
  31. secs := time.Time(t).UnixNano() / 1000000
  32. return []byte(strconv.FormatInt(secs, 10)), nil
  33. }