Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions types/date.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ func (d Date) String() string {
return d.Format(DateFormat)
}

func (d Date) MarshalText() ([]byte, error) {
return []byte(d.Format(DateFormat)), nil
}

func (d *Date) UnmarshalText(data []byte) error {
parsed, err := time.Parse(DateFormat, string(data))
if err != nil {
Expand Down
41 changes: 41 additions & 0 deletions types/date_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package types

import (
"encoding/json"
"encoding/xml"
"fmt"
"testing"
"time"
Expand Down Expand Up @@ -53,6 +54,46 @@ func TestDate_Stringer(t *testing.T) {
})
}

func TestDate_MarshalText(t *testing.T) {
date := Date{Time: time.Date(2022, 6, 14, 0, 0, 0, 0, time.UTC)}

value, err := date.MarshalText()

assert.NoError(t, err)
assert.Equal(t, "2022-06-14", string(value))
}

func TestDate_TextRoundTrip(t *testing.T) {
testDate := time.Date(2022, 6, 14, 0, 0, 0, 0, time.UTC)

value, err := Date{Time: testDate}.MarshalText()
assert.NoError(t, err)

date := Date{}
err = date.UnmarshalText(value)

assert.NoError(t, err)
assert.Equal(t, testDate, date.Time)
}

func TestDate_XMLRoundTrip(t *testing.T) {
testDate := time.Date(2019, 4, 1, 0, 0, 0, 0, time.UTC)
type body struct {
XMLName xml.Name `xml:"body"`
DateField Date `xml:"date"`
}

xmlBytes, err := xml.Marshal(body{DateField: Date{testDate}})
assert.NoError(t, err)
assert.Equal(t, `<body><date>2019-04-01</date></body>`, string(xmlBytes))

var b body
err = xml.Unmarshal(xmlBytes, &b)

assert.NoError(t, err)
assert.Equal(t, testDate, b.DateField.Time)
}

func TestDate_UnmarshalText(t *testing.T) {
testDate := time.Date(2022, 6, 14, 0, 0, 0, 0, time.UTC)
value := []byte("2022-06-14")
Expand Down