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()) +}