Skip to content
This repository has been archived by the owner on Dec 21, 2023. It is now read-only.

Commit

Permalink
feat: Added helper functions to parse timestamps (#342)
Browse files Browse the repository at this point in the history
Signed-off-by: Florian Bacher <[email protected]>
  • Loading branch information
bacherfl authored Oct 13, 2021
1 parent f779369 commit c6f17c0
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
14 changes: 14 additions & 0 deletions pkg/common/timeutils/timeutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
)

const KeptnTimeFormatISO8601 = "2006-01-02T15:04:05.000Z"
const fallbackTimeformat = "2006-01-02T15:04:05.000000000Z"

const defaultEvaluationTimeframe = "5m"

Expand All @@ -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
Expand Down
56 changes: 56 additions & 0 deletions pkg/common/timeutils/timeutils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package timeutils

import (
"github.com/stretchr/testify/require"
"reflect"
"testing"
"time"
)
Expand Down Expand Up @@ -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)
}
})
}
}

0 comments on commit c6f17c0

Please sign in to comment.