時間戳轉換成utc Go語言中常用的時間處理

2021-10-11 16:53:19 字數 2785 閱讀 9492

程式設計過程中,一般都會設定到時間的處理。在go語言中,需要用到time這個包來處理

預設列印出當前機器上的時間和時區。

package mainimport (    "fmt"    "time")func main()
go裡面時間格式化是要按照的一定的格式來,而且這個格式就是乙個日期時間,可以在包裡面找到對應的列舉變數

const (    ansic       = "mon jan _2 15:04:05 2006"    unixdate    = "mon jan _2 15:04:05 mst 2006"    rubydate    = "mon jan 02 15:04:05 -0700 2006"    rfc822      = "02 jan 06 15:04 mst"    rfc822z     = "02 jan 06 15:04 -0700" // rfc822 with numeric zone    rfc850      = "monday, 02-jan-06 15:04:05 mst"    rfc1123     = "mon, 02 jan 2006 15:04:05 mst"    rfc1123z    = "mon, 02 jan 2006 15:04:05 -0700" // rfc1123 with numeric zone    rfc3339     = "2006-01-02t15:04:05z07:00"    rfc3339nano = "2006-01-02t15:04:05.999999999z07:00"    kitchen     = "3:04pm"    // handy time stamps.    stamp      = "jan _2 15:04:05"    stampmilli = "jan _2 15:04:05.000"    stampmicro = "jan _2 15:04:05.000000"    stampnano  = "jan _2 15:04:05.000000000")
可以直接使用上面的變數,也可以自己寫字串,但是位置一定要正確,不然格式化出來的時間就是錯誤的。

fmt.println(time.now().format(time.rfc1123))fmt.println(time.now().format("2006-01-02 15:04:05"))
可以根據單獨的字串,取出對應的年月日,也可以直接使用提供的函式獲取。

fmt.println(now.year(), now.month(), now.hour(), now.minute(), now.second(),now.weekday())
更多函式

預設是取當前時區的時間,也可以轉換成utc或者其他時區的時間。

loc, _ := time.loadlocation("america/los_angeles")fmt.println("america/los_angeles time :", now.in(loc))fmt.println("utc time :", now.utc())
預設是可以轉換成utc時間

stringtime, err := time.parse("2006-01-02 15:04:05", timestring)if err != nil fmt.println(stringtime)
如果需要轉換成指定時區的時間,需要使用parseinlocation

locstringtime, err := time.parseinlocation("2006-01-02 15:04:05", timestring, time.local)if err != nil fmt.println(locstringtime)
time.local獲取到的是本地的時區。

// func sleep(d duration)   休眠多少時間,休眠時處於阻塞狀態,後續程式無法執行    time.sleep(time.duration(10) * time.second)    // func after(d duration)

時間戳轉換成時間

獲得當前時間戳,long型別 long timestamp system.currenttimemillis 要轉換成的時間格式 dateformat sdf new dateformat yyyy mm dd hh mm ss string sd sdf.format new date times...

時間轉換成時間戳

使用unix timestamp這個函式實現時間轉換成時間戳 mysql中的unix timestamp函式有兩種型別供呼叫 1 無引數呼叫 unix timestamp 返回值 自 1970 01 01 00 00 00 的到當前時間的秒數差 例子 select unix timestamp 13...

C語言中時間戳轉換成時間字串的方法

在pe格式裡有個字段是檔案的建立時間戳,我想把轉成字串,這樣看的更直觀。tchar buffer 50 struct tm tm time t time time t ntheader fileheader.timedatestamp 時間戳 g time printf buffer,text d年...