diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b9ef394 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +test: + go test diff --git a/util.go b/util.go index ac13284..d078a90 100644 --- a/util.go +++ b/util.go @@ -70,16 +70,22 @@ func CopyFile(src, dst string) (err error) { return } -func TimeFromUnixMilli(ms int64) time.Time { - const millisInSecond = 1000 - const nsInSecond = 1000000 - return time.Unix(ms/int64(millisInSecond), (ms%int64(millisInSecond))*int64(nsInSecond)) +const milliInSecond int64 = 1000 +const microInSecond int64 = 1000000 +const nsInSecond int64 = 1000000000 + +func TimeFromUnixMilli(input int64) time.Time { + var wholeSeconds int64 = input / milliInSecond + var remainderMillis int64 = input - (wholeSeconds * milliInSecond) + var remainderNano int64 = remainderMillis * 1000000 + return time.Unix(wholeSeconds, remainderNano) } -func TimeFromUnixMicro(ms int64) time.Time { - const microInSecond = 1000000 - const nsInSecond = 1000000 - return time.Unix(ms/int64(microInSecond), (ms%int64(microInSecond))*int64(nsInSecond)) +func TimeFromUnixMicro(input int64) time.Time { + var wholeSeconds int64 = input / microInSecond + var remainderMicros int64 = input - (wholeSeconds * microInSecond) + var remainderNano int64 = remainderMicros * 1000 + return time.Unix(wholeSeconds, remainderNano) } func TimeFromWebKit(input int64) time.Time { diff --git a/util_test.go b/util_test.go new file mode 100644 index 0000000..1cba94f --- /dev/null +++ b/util_test.go @@ -0,0 +1,51 @@ +package goutil + +import ( + "testing" + "time" +) + +func TestFromUnixMilli(t *testing.T) { + ms := 1542810446506 + ts := TimeFromUnixMilli(int64(ms)) + if ts.UTC().String() != "2018-11-21 14:27:26.506 +0000 UTC" { + t.Errorf("Expected time to be '2018-11-21 14:27:26.506 +0000 UTC' got '%s'", ts.UTC().String()) + } +} + +func TestFromUnixMicro(t *testing.T) { + ms := 1542810446506000 + ts := TimeFromUnixMicro(int64(ms)) + if ts.UTC().String() != "2018-11-21 14:27:26.506 +0000 UTC" { + t.Errorf("Expected time to be '2018-11-21 14:27:26.506 +0000 UTC' got '%s'", ts.UTC().String()) + } +} + +func TestFromWebkit(t *testing.T) { + var wk int64 = 13245202142853170 + ts := TimeFromWebKit(wk) + expected := "2020-09-21 22:49:02.85317 +0000 UTC" + if ts.UTC().String() != expected { + t.Errorf("Expected time to be '%s' got '%s'", expected, ts.UTC().String()) + } +} + +func TestNowUnixMicro(t *testing.T) { + now := time.Now() + nownano := now.UnixNano() + nowmicro := nownano / 1000 + ts := TimeFromUnixMicro(nowmicro) + if ts.UTC().String() != now.UTC().String() { + t.Errorf("Expected '%s' got '%s'", now.UTC().String(), ts.UTC().String()) + } +} + +func TestNowUnixMilli(t *testing.T) { + now := time.Now() + nownano := now.UnixNano() + nowmilli := nownano / 1000000 + ts := TimeFromUnixMilli(nowmilli) + if ts.UTC().Format(time.StampMilli) != now.UTC().Format(time.StampMilli) { + t.Errorf("Expected '%s' got '%s'", now.UTC().String(), ts.UTC().String()) + } +}