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
18 changes: 18 additions & 0 deletions types/date.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package types

import (
"encoding/json"
"encoding/xml"
"time"
)

Expand Down Expand Up @@ -29,6 +30,23 @@ func (d *Date) UnmarshalJSON(data []byte) error {
return nil
}

func (d Date) MarshalXML(encoder *xml.Encoder, start xml.StartElement) error {
return encoder.EncodeElement(d.Time.Format(DateFormat), start)
}

func (d *Date) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error {
var dateStr string
if err := decoder.DecodeElement(&dateStr, &start); err != nil {
return err
}
parsed, err := time.Parse(DateFormat, dateStr)
if err != nil {
return err
}
d.Time = parsed
return nil
}

func (d Date) String() string {
return d.Time.Format(DateFormat)
}
Expand Down
24 changes: 24 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 @@ -32,6 +33,29 @@ func TestDate_UnmarshalJSON(t *testing.T) {
assert.Equal(t, testDate, b.DateField.Time)
}

func TestDate_MarshalXML(t *testing.T) {
testDate := time.Date(2019, 4, 1, 0, 0, 0, 0, time.UTC)
b := struct {
DateField Date `xml:"date"`
}{
DateField: Date{testDate},
}
xmlBytes, err := xml.Marshal(b)
assert.NoError(t, err)
assert.Equal(t, `<date>2019-04-01</date>`, string(xmlBytes))
}

func TestDate_UnmarshalXML(t *testing.T) {
testDate := time.Date(2019, 4, 1, 0, 0, 0, 0, time.UTC)
xmlStr := `<date>2019-04-01</date>`
b := struct {
DateField Date `xml:"date"`
}{}
err := xml.Unmarshal([]byte(xmlStr), &b)
assert.NoError(t, err)
assert.Equal(t, testDate, b.DateField.Time)
}

func TestDate_Stringer(t *testing.T) {
t.Run("nil date", func(t *testing.T) {
var d *Date
Expand Down