Skip to content

Commit

Permalink
fix: add check for empty string in ParseDate with tests (#116)
Browse files Browse the repository at this point in the history
  • Loading branch information
pyrooka authored May 21, 2021
1 parent e03d410 commit 35cd647
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
6 changes: 6 additions & 0 deletions v5/core/datetime.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,12 @@ func NormalizeDateTimeUTC(t time.Time) time.Time {
}

// ParseDate parses the specified RFC3339 full-date string (YYYY-MM-DD) and returns a strfmt.Date instance.
// If the string is empty the return value will be the unix epoch (1970-01-01).
func ParseDate(dateString string) (fmtDate strfmt.Date, err error) {
if dateString == "" {
return strfmt.Date(time.Unix(0, 0).UTC()), nil
}

formattedTime, err := time.Parse(strfmt.RFC3339FullDate, dateString)
if err == nil {
fmtDate = strfmt.Date(formattedTime)
Expand All @@ -82,6 +87,7 @@ func ParseDate(dateString string) (fmtDate strfmt.Date, err error) {
}

// ParseDateTime parses the specified date-time string and returns a strfmt.DateTime instance.
// If the string is empty the return value will be the unix epoch (1970-01-01T00:00:00.000Z).
func ParseDateTime(dateString string) (strfmt.DateTime, error) {
return strfmt.ParseDateTime(dateString)
}
8 changes: 8 additions & 0 deletions v5/core/datetime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,10 @@ func TestDateTimeUtil(t *testing.T) {
assert.Equal(t, strfmt.Date{}, fmtDate)
assert.NotNil(t, err)

fmtDate, err = ParseDate("")
assert.Equal(t, strfmt.Date(time.Unix(0, 0).UTC()), fmtDate)
assert.Nil(t, err)

dateTimeVar := strfmt.DateTime(time.Now())
var fmtDTime strfmt.DateTime
fmtDTime, err = ParseDateTime(dateTimeVar.String())
Expand All @@ -181,4 +185,8 @@ func TestDateTimeUtil(t *testing.T) {
fmtDTime, err = ParseDateTime("not a datetime")
assert.Equal(t, strfmt.DateTime{}, fmtDTime)
assert.NotNil(t, err)

fmtDTime, err = ParseDateTime("")
assert.Equal(t, strfmt.NewDateTime(), fmtDTime)
assert.Nil(t, err)
}

0 comments on commit 35cd647

Please sign in to comment.