diff --git a/common.go b/common.go index 47c255c6..0c8a2b1b 100644 --- a/common.go +++ b/common.go @@ -21,6 +21,7 @@ import ( "os" "strconv" "strings" + "time" ) const ( @@ -320,3 +321,16 @@ func OutputCSV(path string, data [][]string) error { defer writer.Flush() return nil } + +func UnixTimestampToTime(timeint64 int64) time.Time { + return time.Unix(timeint64, 0) +} + +func UnixTimestampStrToTime(timeStr string) (time.Time, error) { + i, err := strconv.ParseInt(timeStr, 10, 64) + if err != nil { + return time.Time{}, err + } + + return time.Unix(i, 0), nil +} diff --git a/common_test.go b/common_test.go index 653e2ffb..e4309b99 100644 --- a/common_test.go +++ b/common_test.go @@ -5,6 +5,7 @@ import ( "fmt" "reflect" "testing" + "time" ) func TestIsEnabled(t *testing.T) { @@ -244,3 +245,28 @@ func TestExtractPort(t *testing.T) { t.Error(fmt.Sprintf("Test failed. Expected '%d'. Actual '%d'.", expectedOutput, actualResult)) } } + +func TestUnixTimestampToTime(t *testing.T) { + t.Parallel() + testTime := int64(1489439831) + tm := time.Unix(testTime, 0) + expectedOutput := "2017-03-13 21:17:11 +0000 UTC" + actualResult := UnixTimestampToTime(testTime) + if tm.String() != actualResult.String() { + t.Error(fmt.Sprintf("Test failed. Expected '%s'. Actual '%s'.", expectedOutput, actualResult)) + } +} + +func TestUnixTimestampStrToTime(t *testing.T) { + t.Parallel() + testTime := "1489439831" + expectedOutput := "2017-03-13 21:17:11 +0000 UTC" + actualResult, err := UnixTimestampStrToTime(testTime) + if err != nil { + t.Error(err) + } + + if actualResult.UTC().String() != expectedOutput { + t.Error(fmt.Sprintf("Test failed. Expected '%s'. Actual '%s'.", expectedOutput, actualResult)) + } +}