如何在Golang中获取其他时区的当前时间戳?

huangapple go评论83阅读模式
英文:

How to get the current timestamp in other timezones in Golang?

问题

我需要在不同的时区获取当前时间。

目前我知道我们可以这样做:

t := time.Now()
fmt.Println("Location:", t.Location(), ":Time:", t)
utc, err := time.LoadLocation("America/New_York")
if err != nil {
    fmt.Println("err:", err.Error())
}
fmt.Println("Location:", utc, ":Time:", t.In(utc))

LoadLocation函数的参数是一个与IANA时区数据库中的文件对应的位置名称,例如"America/New_York"。

如果给定国家名称或者GMT偏移量(例如印度的+530),是否有更简单的方法来获取当前时间?

编辑:我还希望支持夏令时。

英文:

I need to get the current time in different time-zones.

Currently I know that we can do the following:

t := time.Now()
fmt.Println("Location:", t.Location(), ":Time:", t)
utc, err := time.LoadLocation("America/New_York")
if err != nil {
	fmt.Println("err: ", err.Error())
}
fmt.Println("Location:", utc, ":Time:", t.In(utc))

The LoadLocation name is taken to be a location name corresponding to a file in the IANA Time Zone database, such as "America/New_York".

Is there a simpler way to get the current time, if the country name, or the GMT offset is given e.g +530 for India?

Edit: I would also want to support Day light savings.

答案1

得分: 117

//初始化时区
loc, _ := time.LoadLocation("Asia/Shanghai")

//设置时区
now := time.Now().In(loc)

英文:
//init the loc
loc, _ := time.LoadLocation("Asia/Shanghai")

//set timezone,  
now := time.Now().In(loc)

答案2

得分: 18

不,那是最好的方法。你可以使用FixedZone创建自定义的Location,然后使用该自定义位置。

FixedZone返回一个始终使用给定时区名称和偏移量(相对于UTC的秒数)的位置。

英文:

No, that is the best way. You can create your custom Location using FixedZone and use that custom location.

> FixedZone returns a Location that always uses the given zone name and
> offset (seconds east of UTC).

答案3

得分: 2

我喜欢这种方式

//初始化时区
loc, _ := time.LoadLocation("Asia/Shanghai")

//设置时区
now := time.Now().In(loc)

我可以在哪里找到位置的名称?

你可以在zoneinfo.zip中找到它

一些示例

package _test

import (
	"fmt"
	"testing"
	"time"
)

func TestTime(t *testing.T) {
	myT := time.Date(2022, 4, 28, 14, 0, 0, 0, time.UTC)
	for _, d := range []struct {
		name     string
		expected string
	}{
		{"UTC", "2022-04-28 14:00:00 +0000 UTC"},
		{"America/Los_Angeles", "2022-04-28 07:00:00 -0700 PDT"},
		{"Asia/Tokyo", "2022-04-28 23:00:00 +0900 JST"},
		{"Asia/Taipei", "2022-04-28 22:00:00 +0800 CST"},
		{"Asia/Hong_Kong", "2022-04-28 22:00:00 +0800 HKT"},
		{"Asia/Shanghai", "2022-04-28 22:00:00 +0800 CST"},
	}{
		loc, _ := time.LoadLocation(d.name)
		if val := fmt.Sprintf("%s", myT.In(loc)); val != d.expected {
			fmt.Println(val)
			t.FailNow()
		}
	}
}
英文:

I like this way

//init the loc
loc, _ := time.LoadLocation("Asia/Shanghai")

//set timezone,  
now := time.Now().In(loc)

Where can I find the name of the location?

> You can see it on the zoneinfo.zip

some example

package _test

import (
	"fmt"
	"testing"
	"time"
)

func TestTime(t *testing.T) {
	myT := time.Date(2022, 4, 28, 14, 0, 0, 0, time.UTC)
	for _, d := range []struct {
		name     string
		expected string
	}{
		{"UTC", "2022-04-28 14:00:00 +0000 UTC"},
		{"America/Los_Angeles", "2022-04-28 07:00:00 -0700 PDT"},
		{"Asia/Tokyo", "2022-04-28 23:00:00 +0900 JST"},
		{"Asia/Taipei", "2022-04-28 22:00:00 +0800 CST"},
		{"Asia/Hong_Kong", "2022-04-28 22:00:00 +0800 HKT"},
		{"Asia/Shanghai", "2022-04-28 22:00:00 +0800 CST"},
	} {
		loc, _ := time.LoadLocation(d.name)
		if val := fmt.Sprintf("%s", myT.In(loc)); val != d.expected {
			fmt.Println(val)
			t.FailNow()
		}
	}
}

答案4

得分: 0

这里没有提到的一点是如何将一个 time.Time 值从一个位置或时区切换到另一个位置或时区。以下是我是如何做的:

time.Local = time.UTC // 将所有时间值默认设置为 UTC

func California() *time.Location {
    la, err := time.LoadLocation("America/Los_Angeles")
    if err != nil {
        panic("在生成洛杉矶当前时间时不应出错")
    }
    return la
}

func Chicago() *time.Location {
    chicago, err := time.LoadLocation("America/Chicago")
    if err != nil {
        panic("在生成芝加哥当前时间时不应出错")
    }

    return chicago
}

caNow := time.Now().In(California()) // 获取洛杉矶当前时间
chiNow := time.Now().In(Chicago()) // 获取芝加哥当前时间

otherChiNow := caNow.In(Chicago()) // 将洛杉矶时间转换为芝加哥时间

希望这能帮到你!

英文:

Something not mentioned here is how to switch a time.Time value from one location or timezone to another location or timezone. Here's how I did it:

time.Local = time.UTC // default to UTC for all time values
func California() *time.Location {
la, err := time.LoadLocation("America/Los_Angeles")
if err != nil {
panic("should not error on generating current time in la")
}
return la
}
func Chicago() *time.Location {
chicago, err := time.LoadLocation("America/Chicago")
if err != nil {
panic("should not error on generating current time in chicago")
}
return chicago
}
caNow := time.Now().In(California()) // get Now in California
chiNow := time.Now().In(Chicago()) // get Now in Chicago
otherChiNow := caNow.In(Chicagio()) // convert CA time to CHI time

huangapple
  • 本文由 发表于 2015年1月17日 03:47:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/27991671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定