AdSense

網頁

2022/1/21

Golang UTC時間與本地時間轉換 UTC and local time conversion

Go time.Time本地時間與UTC時間轉換的方式如下。。


範例環境:

  • Go 1.17
  • 主機位置:台北(Asia/Taipei)


範例

使用time.Now()取得現在的本地時間,也就是我所在的位置台灣時區(Asia/Taipei)。

使用Time.UTC()轉換時間為UTC時間。

調用time.LoadLocation(name string)並輸入時區名稱(IANA Time Zone database中定義的時區名稱)取得Location物件,然後傳入Time.In()轉換目前的時間為特定時區的時間。

main.go

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now() // local time
    fmt.Printf("Now: %v\n", now)

    utc := now.UTC() // UTC time
    fmt.Printf("UTC: %v\n", utc)

    local := utc.In(time.Local) // UTC to local time
    fmt.Printf("Local: %v\n", local)

    loc, _ := time.LoadLocation("Local")
    local = utc.In(loc) // UTC to local time
    fmt.Printf("Local: %v\n", local)

    loc, _ = time.LoadLocation("Asia/Taipei")
    taipei := utc.In(loc) // UTC to "Aisa/Taipei" time
    fmt.Printf("Taipei: %v\n", taipei)

    loc, _ = time.LoadLocation("America/Los_Angeles")
    la := utc.In(loc) // UTC to "America/Los_Angeles" time
    fmt.Printf("Los Angeles: %v\n", la)

    loc, _ = time.LoadLocation("America/New_York")
    ny := utc.In(loc) // UTC to "America/New_York" time
    fmt.Printf("New York: %v\n", ny)

    loc, _ = time.LoadLocation("Japan")
    jp := utc.In(loc) // UTC to "Japan" time
    fmt.Printf("Japan: %v\n", jp)

    utc = taipei.UTC() // Taipei to UTC
    fmt.Printf("UTC: %v\n", utc)

}


測試

執行印出以下。

Now: 2022-01-22 12:10:35.008434 +0800 CST m=+0.000436014
UTC: 2022-01-22 04:10:35.008434 +0000 UTC
Local: 2022-01-22 12:10:35.008434 +0800 CST
Local: 2022-01-22 12:10:35.008434 +0800 CST
Taipei: 2022-01-22 12:10:35.008434 +0800 CST
Los Angeles: 2022-01-21 20:10:35.008434 -0800 PST
New York: 2022-01-21 23:10:35.008434 -0500 EST
Japan: 2022-01-22 13:10:35.008434 +0900 JST
UTC: 2022-01-22 04:10:35.008434 +0000 UTC


沒有留言:

AdSense