我们可以借助 Location() 函数获取当前日期和时间以及本地时间戳,借助 LoadLocation() 函数获取 Golang 中的其他时区。 LoadLocation() 接受一个字符串(城市名称)作为参数并返回地点。location() 不接受任何参数并返回位置。time.now() 返回当前日期和时间以及本地时间戳。

1。 location():不带参数,返回当地时间。

2。 func LoadLocation(name string) (*Location, error):以地名作为参数。返回具有给定名称的位置或返回 nil 作为错误。

3。 time.Now() : 返回当前时间。

示例 1:

package main
  import (
    "fmt"
    "time"
)
  //main function
func main() {
      // with the help of time.Now()
    // store the local time
    t := time.Now()
          // print location and local time
    fmt.Println("Location : ", t.Location(), " Time : ", t)
}

输出:

Location :  Local  Time :  2009-11-10 23:00:00 +0000 UTC m=+0.000000001

示例 2:

package main
  import (
    "fmt"
    "time"
)
  // main function
func main() {
      // with the help of time.Now() 
    // store the local time
    t := time.Now()
          // print location and local time
    location, err := time.LoadLocation("America/New_York")
    if err != nil {
        fmt.Println(err)
    }
          // America/New_York
    fmt.Println("Location : ", location, " Time : ", t.In(location)) 
}

输出:

Location :  America/New_York  Time :  2009-11-10 18:00:00 -0500 EST