@@ -11,6 +11,7 @@ import (
1111 "sort"
1212 "strconv"
1313 "strings"
14+ "time"
1415)
1516
1617var (
@@ -40,6 +41,9 @@ type Options struct {
4041 // when it's safe. This is useful for diffing two structures, where pointer variables would cause
4142 // false changes. However, circular graphs are still detected and elided to avoid infinite output.
4243 DisablePointerReplacement bool
44+
45+ // FormatTime, if true, will format [time.Time] values.
46+ FormatTime bool
4347}
4448
4549// Config is the default config used when calling Dump
@@ -59,6 +63,7 @@ type dumpState struct {
5963 parentPointers ptrmap
6064 currentPointer * ptrinfo
6165 homePackageRegexp * regexp.Regexp
66+ timeFormatter func (t time.Time ) string
6267}
6368
6469func (s * dumpState ) write (b []byte ) {
@@ -129,6 +134,12 @@ func (s *dumpState) dumpSlice(v reflect.Value) {
129134}
130135
131136func (s * dumpState ) dumpStruct (v reflect.Value ) {
137+ val := v .Interface ()
138+ if t , ok := val .(time.Time ); ok && s .timeFormatter != nil {
139+ s .writeString (s .timeFormatter (t ))
140+ return
141+ }
142+
132143 dumpPreamble := func () {
133144 s .dumpType (v )
134145 s .write ([]byte ("{" ))
@@ -246,7 +257,6 @@ func (s *dumpState) dumpChan(v reflect.Value) {
246257}
247258
248259func (s * dumpState ) dumpCustom (v reflect.Value , buf * bytes.Buffer ) {
249-
250260 // Dump the type
251261 s .dumpType (v )
252262
@@ -293,6 +303,8 @@ func (s *dumpState) dump(value interface{}) {
293303 s .dumpVal (v )
294304}
295305
306+ var dumperType = reflect .TypeOf ((* Dumper )(nil )).Elem ()
307+
296308func (s * dumpState ) descendIntoPossiblePointer (value reflect.Value , f func ()) {
297309 canonicalize := true
298310 if isPointerValue (value ) {
@@ -345,7 +357,6 @@ func (s *dumpState) dumpVal(value reflect.Value) {
345357 }
346358
347359 // Handle custom dumpers
348- dumperType := reflect .TypeOf ((* Dumper )(nil )).Elem ()
349360 if v .Type ().Implements (dumperType ) {
350361 s .descendIntoPossiblePointer (v , func () {
351362 // Run the custom dumper buffering the output
@@ -464,6 +475,16 @@ func newDumpState(value reflect.Value, options *Options, writer io.Writer) *dump
464475 w : writer ,
465476 }
466477
478+ if options .FormatTime {
479+ result .timeFormatter = func (t time.Time ) string {
480+ t = t .In (time .UTC )
481+ return fmt .Sprintf (
482+ `time.Date(%d, %d, %d, %d, %d, %d, %d, time.UTC)` ,
483+ t .Year (), t .Month (), t .Day (), t .Hour (), t .Minute (), t .Second (), t .Nanosecond (),
484+ )
485+ }
486+ }
487+
467488 if options .HomePackage != "" {
468489 result .homePackageRegexp = regexp .MustCompile (fmt .Sprintf ("\\ b%s\\ ." , options .HomePackage ))
469490 }
0 commit comments