Skip to content

Commit

Permalink
chore(internal): parse date-time strings more leniently (#94)
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-bot authored Jan 29, 2024
1 parent cab5fe5 commit 8f4dafc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
27 changes: 23 additions & 4 deletions internal/apijson/decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,11 +471,30 @@ func (d *decoder) newTimeTypeDecoder(t reflect.Type) decoderFunc {
format := d.dateFormat
return func(n gjson.Result, v reflect.Value) error {
parsed, err := time.Parse(format, n.Str)
if err != nil {
return err
if err == nil {
v.Set(reflect.ValueOf(parsed).Convert(t))
return nil
}
v.Set(reflect.ValueOf(parsed).Convert(t))
return nil

layouts := []string{
"2006-01-02",
"2006-01-02T15:04:05Z07:00",
"2006-01-02T15:04:05Z0700",
"2006-01-02T15:04:05",
"2006-01-02 15:04:05Z07:00",
"2006-01-02 15:04:05Z0700",
"2006-01-02 15:04:05",
}

for _, layout := range layouts {
parsed, err := time.Parse(layout, n.Str)
if err == nil {
v.Set(reflect.ValueOf(parsed).Convert(t))
return nil
}
}

return fmt.Errorf("unable to leniently parse date-time string: %s", n.Str)
}
}

Expand Down
8 changes: 7 additions & 1 deletion internal/apijson/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,13 @@ var tests = map[string]struct {
"ptr_float_1.54": {"1.54", P(float32(1.54))},
"ptr_float_1.89": {"1.89", P(float64(1.89))},

"date_time": {`"2007-03-01T13:00:00Z"`, time.Date(2007, time.March, 1, 13, 0, 0, 0, time.UTC)},
"date_time": {`"2007-03-01T13:00:00Z"`, time.Date(2007, time.March, 1, 13, 0, 0, 0, time.UTC)},
"date_time_nano_coerce": {`"2007-03-01T13:03:05.123456789Z"`, time.Date(2007, time.March, 1, 13, 3, 5, 123456789, time.UTC)},

"date_time_missing_t_coerce": {`"2007-03-01 13:03:05Z"`, time.Date(2007, time.March, 1, 13, 3, 5, 0, time.UTC)},
"date_time_missing_timezone_coerce": {`"2007-03-01T13:03:05"`, time.Date(2007, time.March, 1, 13, 3, 5, 0, time.UTC)},
"date_time_missing_timezone_colon_coerce": {`"2007-03-01T13:03:05+0100"`, time.Date(2007, time.March, 1, 13, 3, 5, 0, time.FixedZone("", 60*60))},
"date_time_nano_missing_t_coerce": {`"2007-03-01 13:03:05.123456789Z"`, time.Date(2007, time.March, 1, 13, 3, 5, 123456789, time.UTC)},

"map_string": {`{"foo":"bar"}`, map[string]string{"foo": "bar"}},
"map_interface": {`{"a":1,"b":"str","c":false}`, map[string]interface{}{"a": float64(1), "b": "str", "c": false}},
Expand Down

0 comments on commit 8f4dafc

Please sign in to comment.