json.go 884 B

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