diff --git a/encode.go b/encode.go index 97b8063e..5baeb0a7 100644 --- a/encode.go +++ b/encode.go @@ -8,6 +8,7 @@ import ( "sort" "strconv" "strings" + "time" "github.com/goccy/go-yaml/ast" "github.com/goccy/go-yaml/internal/errors" @@ -151,6 +152,9 @@ func (e *Encoder) encodeValue(v reflect.Value, column int) (ast.Node, error) { if mapItem, ok := v.Interface().(MapItem); ok { return e.encodeMapItem(mapItem, column) } + if t, ok := v.Interface().(time.Time); ok { + return e.encodeTime(t, column), nil + } } return e.encodeStruct(v, column) case reflect.Map: @@ -342,6 +346,11 @@ func (e *Encoder) isZeroValue(v reflect.Value) bool { return false } +func (e *Encoder) encodeTime(v time.Time, column int) ast.Node { + value := v.Format(time.RFC3339Nano) + return ast.String(token.New(value, value, e.pos(column))) +} + func (e *Encoder) encodeStruct(value reflect.Value, column int) (ast.Node, error) { node := ast.Mapping(token.New("", "", e.pos(column)), e.isFlowStyle) structType := value.Type() diff --git a/encode_test.go b/encode_test.go index 8c9b853d..9e65d17c 100644 --- a/encode_test.go +++ b/encode_test.go @@ -6,6 +6,7 @@ import ( "math" "strconv" "testing" + "time" "github.com/goccy/go-yaml" ) @@ -291,6 +292,20 @@ func TestEncoder(t *testing.T) { "v: あいうえお\nv2: かきくけこ\n", map[string]string{"v": "あいうえお", "v2": "かきくけこ"}, }, + + // time value + { + "v: 0001-01-01T00:00:00Z\n", + map[string]time.Time{"v": time.Time{}}, + }, + { + "v: 0001-01-01T00:00:00Z\n", + map[string]*time.Time{"v": &time.Time{}}, + }, + { + "v: null\n", + map[string]*time.Time{"v": nil}, + }, } for _, test := range tests { var buf bytes.Buffer