Go time库时间戳和时区

235 阅读2分钟

这里想说的是time库时区和时间戳方法,工作中用到了,也属于踩坑了,变换时区并取相应的时间戳。

这里想讲的是time.Unix是和时区无关的,以下是他的注释里面给的说明,Unix()的结果不依赖于他的时区。

这是什么意思呢?我下面做了测试。

// Unix returns t as a Unix time, the number of seconds elapsed
// since January 1, 1970 UTC. The result does not depend on the
// location associated with t.
// Unix-like operating systems often record time as a 32-bit
// count of seconds, but since the method here returns a 64-bit
// value it is valid for billions of years into the past or future.
func (t Time) Unix() int64 {
	return t.unixSec()
}

这是我的测试代码,注释部分是执行结果。


func TestTime(t *testing.T) {
	nowTime := time.Now()

	jpLoc, _ := time.LoadLocation("Asia/Tokyo")
	jpNowTime := nowTime.In(jpLoc)
	fmt.Printf("loc :%v\n", nowTime)
	fmt.Printf("jp :%v\n", jpNowTime)

	//loc :2023-03-15 21:14:27.180517 +0800 CST m=+0.002227834
	fmt.Printf("loc-format :%v\n", nowTime.Format("2006-01-02 15:04:05"))
	//jp :2023-03-15 22:14:27.180517 +0900 JST
	fmt.Printf("jp-format :%v\n", jpNowTime.Format("2006-01-02 15:04:05"))

	// loc-hour :21
	fmt.Printf("loc-hour :%v\n", nowTime.Hour())
	// jp-hour :22
	fmt.Printf("jp-hour :%v\n", jpNowTime.Hour())

	// loc-unix :1678886067
	fmt.Printf("loc-unix :%v\n", nowTime.Unix())
	// jp-unix :1678886067
	fmt.Printf("jp-unix :%v\n", jpNowTime.Unix())

	jpTime, _ := time.Parse("2006-01-02 15:04:05", jpNowTime.Format("2006-01-02 15:04:05"))
	// loc-unix :1678886067
	fmt.Printf("loc-unix :%v\n", nowTime.Unix())
	// jp-unix :1678886067
	fmt.Printf("jp-unix :%v\n", jpNowTime.Unix())
	// loc-in-jp-unix :1678918467
	fmt.Printf("loc-in-jp-unix :%v\n", jpTime.Unix())
}

从上面的执行结果可以看出,一个time变换时区后,获取的format和hour都是新时区的值,但是unix还是老的值,开发中不注意的话这算是一个坑。

如何获取变换时区后的时间戳呢?上面的代码最后部分也给出了用例,就是以新时区的时间创建一个time然后再获取对应的unix。