json.go 800 B

1234567891011121314151617181920212223242526
  1. package timeutils
  2. import (
  3. "errors"
  4. "time"
  5. )
  6. const (
  7. // RFC3339NanoFixed is our own version of RFC339Nano because we want one
  8. // that pads the nano seconds part with zeros to ensure
  9. // the timestamps are aligned in the logs.
  10. RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
  11. // JSONFormat is the format used by FastMarshalJSON
  12. JSONFormat = `"` + time.RFC3339Nano + `"`
  13. )
  14. // FastMarshalJSON avoids one of the extra allocations that
  15. // time.MarshalJSON is making.
  16. func FastMarshalJSON(t time.Time) (string, error) {
  17. if y := t.Year(); y < 0 || y >= 10000 {
  18. // RFC 3339 is clear that years are 4 digits exactly.
  19. // See golang.org/issue/4556#c15 for more discussion.
  20. return "", errors.New("time.MarshalJSON: year outside of range [0,9999]")
  21. }
  22. return t.Format(JSONFormat), nil
  23. }