-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7813c87
commit 614747b
Showing
2 changed files
with
86 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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{} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |