Skip to content

Commit

Permalink
feat: add Date type
Browse files Browse the repository at this point in the history
  • Loading branch information
francesconi committed Oct 29, 2024
1 parent 7813c87 commit 614747b
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
44 changes: 44 additions & 0 deletions timex/date.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package timex

import (
"encoding"
"fmt"
"time"
)

type Date struct {
Year int
Month time.Month
Day int
}

func NewDateFromTime(t time.Time) Date {
var d Date
d.Year, d.Month, d.Day = t.Date()
return d
}

func ParseDate(s string) (Date, error) {
t, err := time.Parse(time.DateOnly, s)
if err != nil {
return Date{}, err
}
return NewDateFromTime(t), nil
}

func (d Date) String() string {
return fmt.Sprintf("%04d-%02d-%02d", d.Year, d.Month, d.Day)
}

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

func (d *Date) UnmarshalText(data []byte) error {
var err error
*d, err = ParseDate(string(data))
return err
}

var _ encoding.TextMarshaler = Date{}
var _ encoding.TextUnmarshaler = &Date{}
42 changes: 42 additions & 0 deletions timex/date_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package timex

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/assert"
)

func TestParseDate(t *testing.T) {
tests := []struct {
str string
want Date // if zero, expect an error
}{
{"1962-11-02", Date{1962, 11, 2}},
{"1962-12-31", Date{1962, 12, 31}},
{"0003-02-04", Date{3, 2, 4}},
{"999-01-26", Date{}},
{"", Date{}},
{"1962-01-02x", Date{}},
}

for _, tt := range tests {
got, err := ParseDate(tt.str)
assert.Equal(t, tt.want, got)
if got == (Date{}) {
assert.NotNil(t, err)
}
}
}
func TestMarshalJSON(t *testing.T) {
got, err := json.Marshal(Date{2023, 5, 4})
assert.Nil(t, err)
assert.Equal(t, `"2023-05-04"`, string(got))
}

func TestUnmarshalJSON(t *testing.T) {
var r Date
err := json.Unmarshal([]byte(`"2023-05-04"`), &r)
assert.Nil(t, err)
assert.Equal(t, Date{2023, 5, 4}, r)
}

0 comments on commit 614747b

Please sign in to comment.