go時間戳實例(秒、毫秒、納秒)
go時間戳(秒、毫秒、納秒)
注意點
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 毫秒
總結(jié)
當初剛接觸go的時候,以為go中的 time.Now().Unix() 得到的時間戳是和js中的 new Date().getTime() 的時間戳是一樣的,導致在數(shù)據(jù)傳輸過程中出現(xiàn)了錯誤,還找了半天的bug,鬧出了笑話。
所以說,在使用自己所沒用過的方法時,不能理所當然,一定要先測試一下,這樣總體會更加的節(jié)省時間。
從 go 的 1.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
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Go語言如何利用Mutex保障數(shù)據(jù)讀寫正確
這篇文章主要介紹了互斥鎖的實現(xiàn)機制,以及?Go?標準庫的互斥鎖?Mutex?的基本使用方法,文中的示例代碼講解詳細,需要的小伙伴可以參考一下2023-05-05
golang給函數(shù)參數(shù)設(shè)置默認值的幾種方式小結(jié)(函數(shù)參數(shù)默認值
在日常開發(fā)中我們有時候需要使用默認設(shè)置,下面這篇文章主要給大家介紹了關(guān)于golang給函數(shù)參數(shù)設(shè)置默認值的幾種方式小結(jié)的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-01-01
GoFrame框架garray并發(fā)安全數(shù)組使用開箱體驗
這篇文章主要介紹了GoFrame框架garray并發(fā)安全數(shù)組使用開箱體驗,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
通過手機案例理解Go設(shè)計模式之裝飾器模式的功能屬性
這篇文章主要為大家介紹了Go設(shè)計模式之裝飾器模式的功能屬性,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05
一文搞懂Golang 時間和日期相關(guān)函數(shù)
這篇文章主要介紹了Golang 時間和日期相關(guān)函數(shù),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12

