diff --git a/pkg/common/timeutils/timeutils.go b/pkg/common/timeutils/timeutils.go index 8bcc8f38..4c5c585b 100644 --- a/pkg/common/timeutils/timeutils.go +++ b/pkg/common/timeutils/timeutils.go @@ -7,6 +7,7 @@ import ( ) const KeptnTimeFormatISO8601 = "2006-01-02T15:04:05.000Z" +const fallbackTimeformat = "2006-01-02T15:04:05.000000000Z" const defaultEvaluationTimeframe = "5m" @@ -16,6 +17,19 @@ func GetKeptnTimeStamp(timestamp time.Time) string { return timestamp.Format(KeptnTimeFormatISO8601) } +// ParseTimestamp tries to parse the given timestamp using the ISO8601 format (e.g. '2006-01-02T15:04:05.000Z') +// if this is not possible, the fallback format '2006-01-02T15:04:05.000000000Z' will be used. If this fails as well, an error is returned +func ParseTimestamp(timestamp string) (*time.Time, error) { + parsedTime, err := time.Parse(KeptnTimeFormatISO8601, timestamp) + if err != nil { + parsedTime, err = time.Parse(fallbackTimeformat, timestamp) + if err != nil { + return nil, err + } + } + return &parsedTime, nil +} + type GetStartEndTimeParams struct { StartDate string EndDate string diff --git a/pkg/common/timeutils/timeutils_test.go b/pkg/common/timeutils/timeutils_test.go index 6c9afd5b..b6b819f8 100644 --- a/pkg/common/timeutils/timeutils_test.go +++ b/pkg/common/timeutils/timeutils_test.go @@ -2,6 +2,7 @@ package timeutils import ( "github.com/stretchr/testify/require" + "reflect" "testing" "time" ) @@ -147,3 +148,58 @@ func TestGetStartEndTime(t *testing.T) { }) } } + +func TestParseTimestamp(t *testing.T) { + + correctISO8601Timestamp := "2020-01-02T15:04:05.000Z" + correctFallbackTimestamp := "2020-01-02T15:04:05.000000000Z" + + timeObj, _ := time.Parse(KeptnTimeFormatISO8601, correctISO8601Timestamp) + + type args struct { + timestamp string + } + tests := []struct { + name string + args args + want *time.Time + wantErr bool + }{ + { + name: "correct timestamp provided", + args: args{ + timestamp: correctISO8601Timestamp, + }, + want: &timeObj, + wantErr: false, + }, + { + name: "correct fallback timestamp provided", + args: args{ + timestamp: correctFallbackTimestamp, + }, + want: &timeObj, + wantErr: false, + }, + { + name: "incorrect timestamp provided", + args: args{ + timestamp: "invalid", + }, + want: nil, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := ParseTimestamp(tt.args.timestamp) + if (err != nil) != tt.wantErr { + t.Errorf("ParseTimestamp() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("ParseTimestamp() got = %v, want %v", got, tt.want) + } + }) + } +}