go 时间戳(秒、毫秒、纳秒)

本文解析了JavaScript与Go语言中时间戳的不同单位及其引起的跨语言数据同步问题,强调了测试的重要性,并介绍了Go 1.17及以上版本提供的直接获取毫秒、微秒时间戳的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意点

js得到的时间戳和go得到的时间戳是不一样的,js得到的是以毫秒为单位的,而go得到的是以秒或纳秒为单位的时间戳。
js:

	var timestamp = new Date().getTime()
	console.log(timestamp) //1565084135229 毫秒

go

	now:= time.Now()
	fmt.Println(now.Unix()) // 1565084298 秒
	fmt.Println(now.UnixNano()) // 1565084298178502600 纳秒
	fmt.Println(now.UnixNano() / 1e6) // 1565084298178 毫秒

总结

当初刚接触go的时候,以为go中的 time.Now().Unix() 得到的时间戳是和js中的 new Date().getTime() 的时间戳是一样的,导致在数据传输过程中出现了错误,还找了半天的bug,闹出了笑话。
所以说,在使用自己所没用过的方法时,不能理所当然,一定要先测试一下,这样总体会更加的节省时间。

2022.7.21 更新

go1.17(含)版本后,官方提供了直接获取毫秒,微秒值的方法:


// UnixMilli returns t as a Unix time, the number of milliseconds elapsed since
// January 1, 1970 UTC. The result is undefined if the Unix time in
// milliseconds cannot be represented by an int64 (a date more than 292 million
// years before or after 1970). The result does not depend on the
// location associated with t.
func (t Time) UnixMilli() int64 {
	return t.unixSec()*1e3 + int64(t.nsec())/1e6
}

// UnixMicro returns t as a Unix time, the number of microseconds elapsed since
// January 1, 1970 UTC. The result is undefined if the Unix time in
// microseconds cannot be represented by an int64 (a date before year -290307 or
// after year 294246). The result does not depend on the location associated
// with t.
func (t Time) UnixMicro() int64 {
	return t.unixSec()*1e6 + int64(t.nsec())/1e3
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值