github.com/sijibomii/docker@v0.0.0-20231230191044-5cf6ca554647/pkg/jsonlog/time_marshalling.go (about)

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