欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

go中的時間處理過程

 更新時間:2025年07月03日 14:16:07   作者:alden_ygq  
這篇文章主要介紹了go中的時間處理過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

1 獲取當(dāng)前時間

currentTime:=time.Now()     //獲取當(dāng)前時間,類型是Go的時間類型Time
t1:=time.Now().Year()        //年
t2:=time.Now().Month()       //月
t3:=time.Now().Day()         //日
t4:=time.Now().Hour()        //小時
t5:=time.Now().Minute()      //分鐘
t6:=time.Now().Second()      //秒
t7:=time.Now().Nanosecond()  //納秒
//如果獲取UTC時間,則可以使用time.UTCcurrentTimeData:=time.Date(t1,t2,t3,t4,t5,t6,t7,time.Local) //獲取當(dāng)前時間,返回當(dāng)前時間Time     
fmt.Println(currentTime)       //打印結(jié)果:2017-04-11 12:52:52.794351777 +0800 CST
fmt.Println(t1,t2,t3,t4,t5,t6)     //打印結(jié)果:2017 April 11 12 52 52
fmt.Println(currentTimeData)    //打印結(jié)果:2017-04-11 12:52:52.794411287 +0800 CST

 time.Now()和Date()方法都可以獲取當(dāng)前時間,time.Now()用起來比較簡單,但是Date()可以獲取不同的精確值,如time.Date(t1,t2,t3,t4,t5,t6,0,time.Local)將毫秒省略,精確到秒,結(jié)果為:2017-04-11 12:52:52 +0800 CST。

2 獲取當(dāng)前時間戳

timeUnix:=time.Now().Unix()            //單位s,打印結(jié)果:1491888244
timeUnixNano:=time.Now().UnixNano()  //單位納秒,打印結(jié)果:1491888244752784461

3 獲取當(dāng)前時間的字符串格式

timeStr:=time.Now().Format("2006-01-02 15:04:05")  //當(dāng)前時間的字符串,2006-01-02 15:04:05據(jù)說是golang的誕生時間,固定寫法
fmt.Println(timeStr)    //打印結(jié)果:2017-04-11 13:24:04

4 相互轉(zhuǎn)化

4.1 時間戳轉(zhuǎn)時間字符串 (int64 > string)

timeUnix:=time.Now().Unix()   //已知的時間戳
formatTimeStr:=time.Unix(timeUnix,0).Format("2006-01-02 15:04:05")
fmt.Println(formatTimeStr)   //打印結(jié)果:2017-04-11 13:30:39

4.2 時間字符串轉(zhuǎn)時間(string >  Time)

formatTimeStr="2017-04-11 13:33:37"
formatTime,err:=time.Parse("2006-01-02 15:04:05",formatTimeStr)
if err==nil{
    fmt.Println(formatTime) //打印結(jié)果:2017-04-11 13:33:37 +0000 UTC
}

4.3 時間字符串轉(zhuǎn)時間戳 (string >  int64)

formatTimeStr="2017-04-11 13:33:37"
formatTime,err:=time.Parse("2006-01-02 15:04:05",formatTimeStr)
utime := formatTime.Unix()
if err == nil{
    fmt.Println(utime) //打印結(jié)果:2017-04-11 13:33:37 +0000 UTC
}

5 時間計算

5.1 獲取今天0點0時0分的時間戳

currentTime := time.Now() 
startTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 0, 0, 0, 0, currentTime.Location())
fmt.Println(startTime)
fmt.Println(startTime.Format("2006/01/02 15:04:05")) 

5.2 獲取今天23:59:59秒的時間戳

currentTime := time.Now() 
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location()) 
fmt.Println(endTime) 
fmt.Println(endTime.Format("2006/01/02 15:04:05")) 

5.3 獲取1分鐘之前的時間

m, _ := time.ParseDuration("-1m") 
result := currentTime.Add(m)   
fmt.Println(result)
fmt.Println(result.Format("2006/01/02 15:04:05"))

5.4 獲取1小時之前的時間

m, _ := time.ParseDuration("-1h") 
result := currentTime.Add(m) 
fmt.Println(result) 
fmt.Println(result.Format("2006/01/02 15:04:05")) 

5.5 獲取1分鐘之后的時間

m, _ := time.ParseDuration("1m") 
result := currentTime.Add(m)   
fmt.Println(result) 
fmt.Println(result.Format("2006/01/02 15:04:05")) 

5.6 獲取1小時之后的時間

m, _ := time.ParseDuration("1h") 
result := currentTime.Add(m) 
fmt.Println(result) 
fmt.Println(result.Format("2006/01/02 15:04:05")) 

5.7 計算兩個時間戳之間的時間

afterTime, _ := time.ParseDuration("1h") 
result := currentTime.Add(afterTime)   
beforeTime, _ := time.ParseDuration("-1h") 
result2 := currentTime.Add(beforeTime)   
m := result.Sub(result2)
fmt.Printf("%v 分鐘 \n", m.Minutes())   
h := result.Sub(result2) 
fmt.Printf("%v小時 \n", h.Hours())   
d := result.Sub(result2) 
fmt.Printf("%v 天\n", d.Hours()/24) 

5.8 判斷一個時間是否在一個時間之后

stringTime, _ := time.Parse("2006-01-02 15:04:05", "2019-12-12 12:00:00") 
beforeOrAfter := stringTime.After(time.Now())   

if true == beforeOrAfter {   
fmt.Println("2019-12-12 12:00:00在當(dāng)前時間之后!") 
   } else {  
 fmt.Println("2019-12-12 12:00:00在當(dāng)前時間之前!") 
} 

5.9 判斷一個時間相比另外一個時間過去了多久

startTime := time.Now() 
time.Sleep(time.Second * 5)   
fmt.Println("離現(xiàn)在過去了:", time.Since(startTime)) 

6 time.Sleep睡眠指定時間(小時級到納秒級)

golang的休眠可以使用time包中的Sleep函數(shù)實現(xiàn),本節(jié)主要介紹關(guān)于go time.Sleep睡眠指定時間(小時級到納秒級)相關(guān)實現(xiàn)。

6.1 單位

time.sleep單位為:1ns (納秒)

6.2 轉(zhuǎn)換單位

  • 1納秒 =1000皮秒
  • 1納秒 =0.001 微秒
  • 1納秒 =0.000 001毫秒   
  • 1納秒 =0.000 000 001秒

go用來指定睡眠時間的函數(shù)為time.Sleep,接口為: 

// Sleep pauses the current goroutine for at least the duration d.

// A negative or zero duration causes Sleep to return immediately.

func Sleep(d Duration)

傳入的為一個Duration,所以如果想睡眠5s鐘,不能直接寫 time.Sleep(5) ,而應(yīng)該寫time.Sleep(5 * time.Second)

其中time.Second就是一個Duration類型,表示1s的時間間隔,乘系數(shù)5就得到5s的時間間隔。

除了time.Second外,go還提供了不同的時間單位:

const (
    Nanosecond  Duration = 1
    Microsecond = 1000 * Nanosecond
    Millisecond = 1000 * Microsecond 
    Second = 1000 * Millisecond
    Minute = 60 * Second
    Hour = 60 * Minute
)

其中,

  • Nanosecond表示1納秒的時間間隔
  • Microsecond表示1微妙的時間間隔
  • Millisecond表示1毫秒的時間間隔
  • Second表示1秒的時間間隔
  • Minute表示1分鐘的時間間隔
  • Hour表示1小時的時間間隔

想要睡眠的時間可以使用以上的常量自由組合,比如睡眠1小時10分5秒:

time.Sleep(1*time.Hour + 10*time.Minute + 5*time.Second) 

7 耗時統(tǒng)計

7.1 常規(guī)寫法

package main
import (
    "fmt"
    "time"
)
 
func main() {
    bT := time.Now()            // 開始時間
    time.Sleep(5*time.Second)
    eT := time.Since(bT)      // 從開始到當(dāng)前所消耗的時間
 
    fmt.Println("Run time: ", eT)
}

運行結(jié)果:

Run time:  5.001531s

7.2 原始方式

在函數(shù)起始位置計算當(dāng)前時間,在函數(shù)結(jié)束位置算出耗時。

package main
import (
    "fmt"
    "time"
)
 
func sum(n int) int {
    var total int
    startT := time.Now()//計算當(dāng)前時間    total := 0
        for i:=1; i <= n; i++ {
            total += i
        }
    tc := time.Since(startT)//計算耗時
    fmt.Printf("time cost = %v\n", tc)
        return total
}
func main() {
        count := sum(100)
    fmt.Printf("count = %v\n", count)
}

運行結(jié)果:

time cost = 250ns
count = 5050

7.3 簡潔方法

計算當(dāng)前時間與計算耗時放在兩處,難免顯得丑陋,且不易閱讀。如果有多個函數(shù)需要統(tǒng)計耗時,那么多處書寫重復(fù)的兩行代碼會造成代碼冗余。由于 Golang 提供了函數(shù)延時執(zhí)行的功能,借助 defer ,可以通過函數(shù)封裝的方式來避免代碼冗余。 

package main
import (
    "fmt"
    "time"
)
 
//耗時統(tǒng)計函數(shù)
func timeCost(start time.Time){
    tc:=time.Since(start)
    fmt.Printf("time cost = %v\n", tc)
}
func sum(n int) int {
    defer timeCost(time.Now())
        total := 0
        for i:=1; i <= n; i++ {
            total += i
        }
    return total
}
func main() {
        count := sum(100)
    fmt.Printf("count = %v\n", count)
}

運行結(jié)果:

time cost = 333ns
count = 5050

通過輸出可以看到sum()耗時增加了,因為增加了一次timeCost()函數(shù)調(diào)用。不過相比于函數(shù)封裝帶來的便利與代碼美觀,新增的耗時是微不足道可以接受的。

7.4 優(yōu)雅方法

每次調(diào)用耗時統(tǒng)計函數(shù)timeCost()都需要傳入time.Now(),重復(fù)書寫time.Now()無疑造成了代碼冗余。

在上面的基礎(chǔ)上,進(jìn)行進(jìn)一步的封裝,實現(xiàn)如下:

package main
import (
    "fmt"
    "time"
)
//耗時統(tǒng)計函數(shù)
func timeCost() func() {
    start := time.Now()
    return func() {
        tc:=time.Since(start)
        fmt.Printf("time cost = %v\n", tc)
    }
}
func sum(n int) int {
    defer timeCost()()//注意,是對 timeCost()返回的函數(shù)進(jìn)行調(diào)用,因此需要加兩對小括號
        total := 0
        for i:=1; i <= n; i++ {
            total += i
        }
    return total
}
func main() {
        count := sum(100)
    fmt.Printf("count = %v\n", count)
}

運行結(jié)果:

time cost = 1.204μs
count = 5050

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 線上golang grpc服務(wù)資源泄露問題排查

    線上golang grpc服務(wù)資源泄露問題排查

    這篇文章主要介紹了線上golang grpc服務(wù)資源泄露問題排查,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Golang必知必會之Go?Mod命令詳解

    Golang必知必會之Go?Mod命令詳解

    go mod可以使項目從GOPATH的強(qiáng)制依賴中獨立出來,也就是說你的項目依賴不再需要放在在GOPATH下面了,下面這篇文章主要給大家介紹了關(guān)于Golang必知必會之Go?Mod命令的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • go中new和make的區(qū)別小結(jié)

    go中new和make的區(qū)別小結(jié)

    new 只分配內(nèi)存,make 用于初始化 slice、map 和 channel,本文詳細(xì)的介紹了go中new和make的區(qū)別小結(jié),感興趣的可以了解一下
    2023-05-05
  • Go語言的代碼組織結(jié)構(gòu)詳細(xì)介紹

    Go語言的代碼組織結(jié)構(gòu)詳細(xì)介紹

    這篇文章主要介紹了Go語言的代碼碼組織結(jié)構(gòu)詳細(xì)介紹,即Go語言源碼的文件結(jié)構(gòu),本文講解了包、main和main.main、os包等內(nèi)容,需要的朋友可以參考下
    2014-10-10
  • go語言if/else語句簡單用法示例

    go語言if/else語句簡單用法示例

    這篇文章主要介紹了go語言if/else語句用法,結(jié)合實例形式分析了go語言if else語句的判定與流程控制技巧,需要的朋友可以參考下
    2016-05-05
  • 并發(fā)安全本地化存儲go-cache讀寫鎖實現(xiàn)多協(xié)程并發(fā)訪問

    并發(fā)安全本地化存儲go-cache讀寫鎖實現(xiàn)多協(xié)程并發(fā)訪問

    這篇文章主要介紹了并發(fā)安全本地化存儲go-cache讀寫鎖實現(xiàn)多協(xié)程并發(fā)訪問,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-10-10
  • go并發(fā)編程sync.Cond使用場景及實現(xiàn)原理

    go并發(fā)編程sync.Cond使用場景及實現(xiàn)原理

    這篇文章主要為大家介紹了go并發(fā)編程sync.Cond使用場景及實現(xiàn)原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-08-08
  • 一文深入探索Go語言中的循環(huán)結(jié)構(gòu)

    一文深入探索Go語言中的循環(huán)結(jié)構(gòu)

    在編程中,循環(huán)結(jié)構(gòu)扮演著重要的角色,它使我們能夠有效地重復(fù)執(zhí)行特定的代碼塊,以實現(xiàn)各種任務(wù)和邏輯,在Go語言中,for 是 Go 中唯一的循環(huán)結(jié)構(gòu),本文將深入探討Go語言中的for循環(huán)類型以及它們的用法
    2023-08-08
  • 簡單聊聊Go語言里面的閉包

    簡單聊聊Go語言里面的閉包

    這篇文章主要為大家詳細(xì)介紹了Go語言中閉包的原理與實現(xiàn)的相關(guān)資料,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Go語言有一定幫助,需要的可以參考一下
    2022-11-11
  • Golang解析JSON遇到的坑及解決方法

    Golang解析JSON遇到的坑及解決方法

    這篇文章主要為大家介紹了Golang解析JSON時會遇到的一些坑及解決方法,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Go語言有一點的幫助,需要的可以參考一下
    2023-02-02

最新評論