Time:Go語言的時間處理利器

2023/09/15閱讀時間約 10 分鐘


raw-image

👨‍💻簡介

要處理日期和時間,就必須知道這個Package -> time,Go提供了內建的timePackage。 今天主要介紹time的功能,包括時間操作、格式化等等,以及常見用法。

主要功能

timePackage的主要功能是處理時間和日期的操作,包括時間的表示、創建、格式化和計算。在Go中,時間通常以time.Time type表示,這個type包含了日期和時間的資訊。

導入Package

import "time"

創建時間

使用time.Now()函數來獲取當前的時間。

package main

import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
fmt.Println("Current Time:", currentTime)
}

你還可以使用time.Date()函數來創建一個特定日期和時間的time.Time 物件。

package main

import (
"fmt"
"time"
)
func main() {
specificTime := time.Date(2023, time.September, 15, 12, 0, 0, 0, time.UTC)
fmt.Println("Specific Time:", specificTime)
}

時間格式化

timePackage有提供許多方法來格式化時間為字串。可以使用Format方法和指定的時間格式來實現。

package main

import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
fmt.Println("Default Format:", currentTime)
fmt.Println("Custom Format:", currentTime.Format("2006-01-02 15:04:05"))
}

時間操作

對時間進行增減,如計算兩個時間的差距、增加時間、減少時間等。

package main

import (
"fmt"
"time"
)
func main() {
now := time.Now()
oneHourLater := now.Add(time.Hour)
fmt.Println("One Hour Later:", oneHourLater)

tenMinutesAgo := now.Add(-10 * time.Minute)
fmt.Println("Ten Minutes Ago:", tenMinutesAgo)

duration := oneHourLater.Sub(now)
fmt.Println("Time Difference:", duration)
}

定時器

timePackage還提供了定時器的功能,可以用來執行定時任務。

package main

import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()

for {
select {
case <-ticker.C:
fmt.Println("Tick at", time.Now())
}
}
}

Sleep

要讓程式暫停執行一段時間,可以使用time.Sleep函數。

package main

import (
"fmt"
"time"
)
func main() {
fmt.Println("Start")
time.Sleep(3 * time.Second)
fmt.Println("End after 3 seconds")
}

常見用法

時間比較

使用BeforeAfterEqual方法來比較兩個時間差。

package main

import (
"fmt"
"time"
)
func main() {
now := time.Now()
future := now.Add(time.Hour)

if future.After(now) {
fmt.Println("Future time is after current time")
}

past := now.Add(-time.Hour)

if past.Before(now) {
fmt.Println("Past time is before current time")
}

sameTime := now

if sameTime.Equal(now) {
fmt.Println("Same time as current time")
}
}

計算時間間隔

使用Sub方法計算兩個時間之間的時間間隔。

package main

import (
"fmt"
"time"
)
func main() {
start := time.Now()
time.Sleep(2 * time.Second)
end := time.Now()

duration := end.Sub(start)
fmt.Println("Time elapsed:", duration)
}

時間格式化與解析

將時間格式化為字串,也可以從字串解析出時間。

package main

import (
"fmt"
"time"
)
func main() {
// 格式化時間為字串
currentTime := time.Now()
fmt.Println("Default Format:", currentTime)
fmt.Println("Custom Format:", currentTime.Format("2006-01-02 15:04:05"))

// 從字串解析時間
timeStr := "2023-09-15 14:30:00"
parsedTime, _ := time.Parse("2006-01-02 15:04:05", timeStr)
fmt.Println("Parsed Time:", parsedTime)
}

定義自定義時區

使用time.LoadLocation來定義自定義的時區。

package main

import (
"fmt"
"time"
)
func main() {
// 定義自定義時區
taipei, _ := time.LoadLocation("Asia/Taipei")

// 在指定時區下獲取時間
twTime := time.Now().In(taipei)
fmt.Println("Taiwai Time:", twTime)
}

定時任務

使用time.Timer來執行定時任務,通常用來定時執行程式中的某些操作。

package main

import (
"fmt"
"time"
)
func main() {
timer1 := time.NewTimer(2 * time.Second)
<-timer1.C
fmt.Println("Timer 1 fired")

timer2 := time.NewTimer(time.Second)
go func() {
<-timer2.C
fmt.Println("Timer 2 fired")
}()
stop2 := timer2.Stop()
if stop2 {
fmt.Println("Timer 2 stopped")
}
}

📚參考資料

16會員
74內容數
golang
留言0
查看全部
發表第一個留言支持創作者!