Go时区设置

Python011

Go时区设置,第1张

全球以英国伦敦格林威治作为零度经线的起点,每隔15经度为一个时区,15度经线为该时区的中央经线,共分为24个时区。由西向东每隔15经度增加一个时区,相反的,每向西15经度减少一个时区。中国所在时区为东8区。

当前时间 time.Now() 返回的是当地时区的时间:

CST可以代表如下四个不同的时区:

time.Now() 返回的 +0800 CST 表示的就是中国标准时间,与UTC时间有如下的转化:

Wall Clocks表示挂钟时间,存储的是自1970 年 1 月 1 日 0 时 0 分 0 秒以来的时间戳,当系统和授时服务器进行校准时间时间操作时,有可能造成这一秒是2018-1-1 00:00:00,而下一秒变成了2017-12-31 23:59:59的情况。

Monotonic Clocks,意思是单调时间的,所谓单调,就是只会不停的往前增长,不受校时操作的影响,这个时间是自进程启动以来的秒数。

time.Now() 返回的 m=+0.004002201 就是表示Monotonic Clocks

go语言中如果不设置指定的时区,通过 time.Now() 获取到的就是本地时区

设置时区有两种方式:

固定时区到东八区。但这种不是对程序的全局设置,每次获取时都需要固定时区

加载指定时区。但如果没有go环境使用这种方式就会加载失败,因为时区信息是放在go的安装包中的。

如果你用第二种方式加载时区,在打docker镜像时就需要进行时区相关的配置,配置文件如下:

参考文章:

https://zhuanlan.zhihu.com/p/47754783

https://blog.mimvp.com/article/11887.html

这样。不过只是个精确到纳秒的计时器,不是精确到纳秒的当前时间。windows好像只能拿到ms精度的当前时间吧,不是很清楚。

package main

import (

"syscall"

"time"

"unsafe"

)

func NewStopWatch() func() time.Duration {

var QPCTimer func() func() time.Duration

QPCTimer = func() func() time.Duration {

lib, _ := syscall.LoadLibrary("kernel32.dll")

qpc, _ := syscall.GetProcAddress(lib, "QueryPerformanceCounter")

qpf, _ := syscall.GetProcAddress(lib, "QueryPerformanceFrequency")

if qpc == 0 || qpf == 0 {

return nil

}

var freq, start uint64

syscall.Syscall(qpf, 1, uintptr(unsafe.Pointer(&freq)), 0, 0)

syscall.Syscall(qpc, 1, uintptr(unsafe.Pointer(&start)), 0, 0)

if freq <= 0 {

return nil

}

freqns := float64(freq) / 1e9

return func() time.Duration {

var now uint64

syscall.Syscall(qpc, 1, uintptr(unsafe.Pointer(&now)), 0, 0)

return time.Duration(float64(now-start) / freqns)

}

}

var StopWatch func() time.Duration

if StopWatch = QPCTimer()StopWatch == nil {

// Fallback implementation

start := time.Now()

StopWatch = func() time.Duration { return time.Since(start) }

}

return StopWatch

}

func main() {

// Call a new stop watch to create one from this moment on.

watch := NewStopWatch()

// Do some stuff that takes time.

time.Sleep(1)

// Call the stop watch itself and it will return a time.Duration

dur := watch()

}

这和语言没关系,操作系统要提供这样的原语。linux和windows都是可以的。