From f03dd4ac4ff12f0f05f46554ea7c9b785dc5f74f Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Fri, 10 Nov 2023 12:15:18 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20times=20=E5=8C=85=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E5=85=A8=E5=B1=80=E6=97=B6=E9=97=B4=E5=81=8F?= =?UTF-8?q?=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/times/offset.go | 31 +++++++++++++++++++++++++++++++ utils/times/offset_test.go | 17 +++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 utils/times/offset.go create mode 100644 utils/times/offset_test.go diff --git a/utils/times/offset.go b/utils/times/offset.go new file mode 100644 index 0000000..4d09c05 --- /dev/null +++ b/utils/times/offset.go @@ -0,0 +1,31 @@ +package times + +import ( + "sync" + "time" +) + +var sourceLocation = time.Local +var offsetLock sync.Mutex + +// SetGlobalTimeOffset 设置全局时间偏移量 +func SetGlobalTimeOffset(offset time.Duration) { + offsetLock.Lock() + defer offsetLock.Unlock() + time.Local = sourceLocation + _, currentOffset := time.Now().Zone() + newOffset := currentOffset + int(offset.Seconds()) + location := time.FixedZone("OFFSET", newOffset) + time.Local = location +} + +// NowByNotOffset 获取未偏移的当前时间 +func NowByNotOffset() time.Time { + offsetLock.Lock() + defer offsetLock.Unlock() + offset := time.Local + time.Local = sourceLocation + now := time.Now() + time.Local = offset + return now +} diff --git a/utils/times/offset_test.go b/utils/times/offset_test.go new file mode 100644 index 0000000..3c618bb --- /dev/null +++ b/utils/times/offset_test.go @@ -0,0 +1,17 @@ +package times_test + +import ( + "fmt" + "github.com/kercylan98/minotaur/utils/times" + "testing" + "time" +) + +func TestSetGlobalTimeOffset(t *testing.T) { + fmt.Println(time.Now()) + times.SetGlobalTimeOffset(-times.Hour) + fmt.Println(time.Now()) + times.SetGlobalTimeOffset(times.Hour) + fmt.Println(time.Now()) + fmt.Println(times.NowByNotOffset()) +}