feat: times 包支持设置全局时间偏移

This commit is contained in:
kercylan98 2023-11-10 12:15:18 +08:00
parent 9157c6a309
commit f03dd4ac4f
2 changed files with 48 additions and 0 deletions

31
utils/times/offset.go Normal file
View File

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

View File

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