-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime.go
49 lines (42 loc) · 1.12 KB
/
time.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package pretty
import (
"reflect"
"time"
"github.com/pierrre/pretty/internal/write"
)
// TimeValueWriter is a [ValueWriter] that handles [time.Time] values.
//
// It should be created with [NewTimeValueWriter].
type TimeValueWriter struct {
// Format is the format of the time.
// Default: [time.RFC3339Nano].
Format string
// Location to convert the time before formatting.
// Default: nil (no conversion).
Location *time.Location
}
// NewTimeValueWriter creates a new [TimeValueWriter] with default values.
func NewTimeValueWriter() *TimeValueWriter {
return &TimeValueWriter{
Format: time.RFC3339Nano,
}
}
var timeType = reflect.TypeFor[time.Time]()
// WriteValue implements [ValueWriter].
func (wv *TimeValueWriter) WriteValue(st *State, v reflect.Value) bool {
if v.Type() != timeType {
return false
}
if !v.CanInterface() {
return false
}
tm := v.Interface().(time.Time) //nolint:forcetypeassert // Check above.
if wv.Location != nil {
tm = tm.In(wv.Location)
}
bp := bytesPool.Get()
defer bytesPool.Put(bp)
*bp = tm.AppendFormat((*bp)[:0], wv.Format)
write.Must(st.Writer.Write(*bp))
return true
}