Go语言教程之边写边学:基础练习:如何获取带有本地时区的当前日期和时间

首先,需要配置时区,然后根据时区转换时间,LoadLocation返回具有给定名称的Location。

示例代码:

package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    t := time.Now()
    fmt.Println("Location : ", t.Location(), " Time : ", t) // local time
     
    location, err := time.LoadLocation("America/New_York")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("Location : ", location, " Time : ", t.In(location)) // America/New_York
 
    loc, _ := time.LoadLocation("Asia/Shanghai")
    now := time.Now().In(loc)
    fmt.Println("Location : ", loc, " Time : ", now) // Asia/Shanghai
}

输出:

Location :  Local  Time :  2017-08-26 21:04:56.1874497 +0530 IST
Location :  America/New_York  Time :  2017-08-26 11:34:56.1874497 -0400 EDT
Location :  Asia/Shanghai  Time :  2017-08-26 23:34:56.1884498 +0800 CST