[golang] time.Duration 詳解

在 Go (Golang) 中,time.Duration 是 time 包中的一個類型,用於表示時間間隔。time.Duration 是一個整數類型,底層使用 int64 表示時間的納秒數(nanoseconds)。


基礎概念


1. 定義

time.Duration 表示兩個時間點之間的差距(持續時間),例如幾秒、幾分鐘、幾小時等。

package time

type Duration int64


2. 常量單位

Go 提供了以下常量,用於輕鬆表達不同的時間單位:

const (

Nanosecond  Duration = 1                  // 1 納秒

Microsecond          = 1000 * Nanosecond  // 1 微秒

Millisecond          = 1000 * Microsecond // 1 毫秒

Second               = 1000 * Millisecond // 1 秒

Minute               = 60 * Second        // 1 分鐘

Hour                 = 60 * Minute        // 1 小時

)

這些常量可用於將不同的時間單位轉換為納秒。



使用方式

1. 創建時間間隔

time.Duration 可以通過直接指定數值或計算表達來創建。

package main

import (

"fmt"

"time"

)

func main() {

// 創建時間間隔

duration1 := 2 * time.Second       // 2 秒

duration2 := 1500 * time.Millisecond // 1.5 秒

fmt.Println("Duration1:", duration1)

fmt.Println("Duration2:", duration2)

}

輸出:

Duration1: 2s

Duration2: 1.5s


2. 時間操作

time.Duration 常用於與 time.Time 進行時間加減運算。


package main

import (

"fmt"

"time"

)

func main() {

now := time.Now()                  // 當前時間

future := now.Add(5 * time.Minute) // 增加 5 分鐘

past := now.Add(-10 * time.Second) // 減少 10 秒


fmt.Println("Now:", now)

fmt.Println("Future:", future)

fmt.Println("Past:", past)

}



3. 轉換為不同單位

time.Duration 提供多種方法來將其轉換為不同單位。

方法 描述

Hours() 轉換為小時數(浮點數)

Minutes() 轉換為分鐘數(浮點數)

Seconds() 轉換為秒數(浮點數)

Milliseconds() 轉換為毫秒數(整數)

Microseconds() 轉換為微秒數(整數)

Nanoseconds() 轉換為納秒數(整數)


範例:

package main

import (

"fmt"

"time"

)

func main() {

duration := 5*time.Minute + 30*time.Second // 5 分鐘 30 秒

fmt.Printf("Hours: %.2f\n", duration.Hours())

fmt.Printf("Minutes: %.2f\n", duration.Minutes())

fmt.Printf("Seconds: %.2f\n", duration.Seconds())

fmt.Printf("Milliseconds: %d\n", duration.Milliseconds())

fmt.Printf("Microseconds: %d\n", duration.Microseconds())

fmt.Printf("Nanoseconds: %d\n", duration.Nanoseconds())

}


輸出:

Hours: 0.09

Minutes: 5.50

Seconds: 330.00

Milliseconds: 330000

Microseconds: 330000000

Nanoseconds: 330000000000



4. 格式化輸出

可以使用 String() 方法格式化輸出 time.Duration。

範例:

package main

import (

"fmt"

"time"

)

func main() {

duration := 1*time.Hour + 15*time.Minute + 42*time.Second

fmt.Println("Duration:", duration.String()) // 輸出格式: "1h15m42s"

}


5. 解析字串為時間間隔

time.ParseDuration() 可以用來解析字串形式的時間。

package main

import (

"fmt"

"time"

)

func main() {

duration, err := time.ParseDuration("2h30m15s") // 2 小時 30 分鐘 15 秒

if err != nil {

fmt.Println("Error parsing duration:", err)

return

}

fmt.Println("Parsed Duration:", duration)

}


輸出:

Parsed Duration: 2h30m15s




注意事項

範圍限制:


由於底層是 int64,time.Duration 的範圍是 -2^63 到 2^63-1 納秒,約為 ±292 年。

精度問題:


time.Duration 的精度是 納秒,因此不適合表示超長時間或需要更高精度的時間。


與 time.Time 區別:

       time.Time 表示具體的時間點。

      time.Duration 表示時間段或持續時間。



常見用途

計算執行時間:

start := time.Now()

// 執行一些操作

elapsed := time.Since(start)

fmt.Println("Elapsed time:", elapsed)


限制操作超時:

timeout := 5 * time.Second

time.AfterFunc(timeout, func() {

fmt.Println("Timeout reached")

})


設定間隔執行:

ticker := time.NewTicker(1 * time.Second)

defer ticker.Stop()

for t := range ticker.C {

fmt.Println("Tick at:", t)

}


留言

這個網誌中的熱門文章

[Kotlin]如何學習Kotlin

[golang]如何使用 gorm 高效執行批量插入 (可以透過 Create()、CreateInBatches(),或者 原生 SQL 語句 來提升效率)

[Kotlin]Kotlin Multiplatform (KMP) 如何安裝使用和部署