feat: times 包支持设置全局时间偏移
This commit is contained in:
parent
9157c6a309
commit
f03dd4ac4f
|
@ -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
|
||||
}
|
|
@ -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())
|
||||
}
|
Loading…
Reference in New Issue