time.go 932 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package jsontype
  2. import (
  3. "encoding/json"
  4. "time"
  5. "github.com/globalsign/mgo/bson"
  6. )
  7. // MilliTime represents time.Time that works better with mongodb.
  8. type MilliTime struct {
  9. time.Time
  10. }
  11. // MarshalJSON marshals mt to json bytes.
  12. func (mt MilliTime) MarshalJSON() ([]byte, error) {
  13. return json.Marshal(mt.Milli())
  14. }
  15. // UnmarshalJSON unmarshals data into mt.
  16. func (mt *MilliTime) UnmarshalJSON(data []byte) error {
  17. var milli int64
  18. if err := json.Unmarshal(data, &milli); err != nil {
  19. return err
  20. }
  21. mt.Time = time.Unix(0, milli*int64(time.Millisecond))
  22. return nil
  23. }
  24. // GetBSON returns BSON base on mt.
  25. func (mt MilliTime) GetBSON() (interface{}, error) {
  26. return mt.Time, nil
  27. }
  28. // SetBSON sets raw into mt.
  29. func (mt *MilliTime) SetBSON(raw bson.Raw) error {
  30. return raw.Unmarshal(&mt.Time)
  31. }
  32. // Milli returns milliseconds for mt.
  33. func (mt MilliTime) Milli() int64 {
  34. return mt.UnixNano() / int64(time.Millisecond)
  35. }