github.com/benz9527/xboot@v0.0.0-20240504061247-c23f15593274/lib/hrtime/tz.go (about) 1 package hrtime 2 3 import ( 4 "sync/atomic" 5 "time" 6 ) 7 8 type TimeZoneOffset int32 9 10 const ( 11 hourInMinutes = 3600 12 TzUtc0Offset TimeZoneOffset = 0 13 TzUtc8Offset TimeZoneOffset = 8 * hourInMinutes 14 TzAsiaShanghaiOffset TimeZoneOffset = TzUtc8Offset 15 ) 16 17 var ( 18 defaultTimezoneOffset int32 19 appStartTime time.Time 20 zoneMap = map[TimeZoneOffset]*time.Location{ 21 TzUtc0Offset: time.UTC, 22 TzAsiaShanghaiOffset: time.FixedZone("CST", int(TzAsiaShanghaiOffset)), 23 } 24 ) 25 26 func DefaultTimezoneOffset() int { 27 return int(atomic.LoadInt32(&defaultTimezoneOffset)) 28 } 29 30 func SetDefaultTimezoneOffset(tz TimeZoneOffset) { 31 atomic.StoreInt32(&defaultTimezoneOffset, int32(tz)) 32 } 33 34 // Reduce the location object allocation. 35 func loadTZLocation(offset TimeZoneOffset) *time.Location { 36 loc, ok := zoneMap[offset] 37 if !ok { 38 return time.UTC 39 } 40 return loc 41 } 42 43 func MillisToTzTime(millis int64, tzOffset TimeZoneOffset) time.Time { 44 return time.UnixMilli(millis).In(loadTZLocation(tzOffset)) 45 } 46 47 func MillisToDefaultTzTime(millis int64) time.Time { 48 return time.UnixMilli(millis).In(loadTZLocation(TimeZoneOffset(DefaultTimezoneOffset()))) 49 }