Skip to content

Commit

Permalink
Allow other formats when unmarshalling time
Browse files Browse the repository at this point in the history
  • Loading branch information
ItalyPaleAle committed Feb 14, 2022
1 parent d7da5b0 commit 9a0650b
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 2 deletions.
14 changes: 12 additions & 2 deletions graphql/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,18 @@ func MarshalTime(t time.Time) Marshaler {
}

func UnmarshalTime(v interface{}) (time.Time, error) {
formats := []string{
time.RFC3339Nano,
"2006-01-02 15:04:05.999999999",
"2006-01-02",
}
if tmpStr, ok := v.(string); ok {
return time.Parse(time.RFC3339Nano, tmpStr)
for _, f := range formats {
t, err := time.Parse(f, tmpStr)
if err == nil {
return t, nil
}
}
}
return time.Time{}, errors.New("time should be RFC3339Nano formatted string")
return time.Time{}, errors.New("time is not a string in a recognized format")
}
64 changes: 64 additions & 0 deletions graphql/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,67 @@ func TestTime(t *testing.T) {
require.True(t, initialTime.Equal(newTime), "expected times %v and %v to equal", initialTime, newTime)
})
}

func TestUnmarshalTime(t *testing.T) {
tests := []struct {
name string
in interface{}
want time.Time
wantErr bool
}{
{
name: "RFC3339Nano",
in: "2022-02-10T10:20:30.123456789Z",
want: time.Date(2022, 02, 10, 10, 20, 30, 123456789, time.UTC),
wantErr: false,
},
{
name: "RFC3339",
in: "2022-02-10T10:20:30Z",
want: time.Date(2022, 02, 10, 10, 20, 30, 0, time.UTC),
wantErr: false,
},
{
name: "UTC ISO with time",
in: "2022-02-10 10:20:30",
want: time.Date(2022, 02, 10, 10, 20, 30, 0, time.UTC),
wantErr: false,
},
{
name: "UTC ISO with time and nsec",
in: "2022-02-10 10:20:30.123456789",
want: time.Date(2022, 02, 10, 10, 20, 30, 123456789, time.UTC),
wantErr: false,
},
{
name: "UTC ISO date",
in: "2022-02-10",
want: time.Date(2022, 02, 10, 0, 0, 0, 0, time.UTC),
wantErr: false,
},
{
name: "Invalid format 1",
in: "20220210",
want: time.Time{},
wantErr: true,
},
{
name: "Invalid format 1",
in: "2022-02-33",
want: time.Time{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := UnmarshalTime(tt.in)
if (err != nil) != tt.wantErr {
t.Errorf("UnmarshalTime() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !got.Equal(tt.want) {
t.Errorf("UnmarshalTime() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 9a0650b

Please sign in to comment.