Add common Unix time functions

This commit is contained in:
Adrian Gallagher
2017-03-14 08:43:28 +11:00
parent 3b3847404c
commit e770b5fd71
2 changed files with 40 additions and 0 deletions

View File

@@ -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
}

View File

@@ -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))
}
}