From fcbcf885e99aa8df308c68b1cedb98d3946282eb Mon Sep 17 00:00:00 2001 From: jolheiser Date: Wed, 17 Mar 2021 22:30:56 -0500 Subject: [PATCH] Commit epoch Signed-off-by: jolheiser --- Makefile | 13 +++++++++++++ epoch/epoch.go | 21 +++++++++++++++++++++ epoch/epoch_test.go | 24 ++++++++++++++++++++++++ go.mod | 3 +++ 4 files changed, 61 insertions(+) create mode 100644 Makefile create mode 100644 epoch/epoch.go create mode 100644 epoch/epoch_test.go create mode 100644 go.mod diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0b10ff7 --- /dev/null +++ b/Makefile @@ -0,0 +1,13 @@ +GO ?= go + +.PHONY: vet +vet: + $(GO) vet ./... + +.PHONY: fmt +fmt: + $(GO) fmt ./... + +.PHONY: test +test: + $(GO) test -race ./... diff --git a/epoch/epoch.go b/epoch/epoch.go new file mode 100644 index 0000000..42aba81 --- /dev/null +++ b/epoch/epoch.go @@ -0,0 +1,21 @@ +package epoch + +import "time" + +// Zero passes time.Time.IsZero +const Zero = Epoch(-62135596800) + +// Epoch is a unix timestamp (seconds) +// +// Any time-specific calculations should be done with Epoch.Time +type Epoch int64 + +// Time returns the corresponding time.Time from this Epoch +func (e Epoch) Time() time.Time { + return time.Unix(int64(e), 0) +} + +// Now returns the current Unix Epoch +func Now() Epoch { + return Epoch(time.Now().Unix()) +} diff --git a/epoch/epoch_test.go b/epoch/epoch_test.go new file mode 100644 index 0000000..cebc19e --- /dev/null +++ b/epoch/epoch_test.go @@ -0,0 +1,24 @@ +package epoch + +import ( + "testing" + "time" +) + +const secs = 1616025600 + +func TestEpoch(t *testing.T) { + e := Epoch(secs) + u := time.Unix(secs, 0) + if e.Time() != u { + t.Log("epoch did not match time with matching seconds") + t.FailNow() + } +} + +func TestEpochZero(t *testing.T) { + if !Zero.Time().IsZero() { + t.Log("epoch did not match zero-time") + t.FailNow() + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..59164f2 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module go.jolheiser.com/go-common + +go 1.16