Golang如何根据国家代码获取时区信息

Golang如何根据国家代码获取时区信息 我是Golang新手,正在将一个函数从PHP转换到Golang。

我想在Golang中根据国家代码获取时区信息。这类似于PHP中的这个函数:

public static array DateTimeZone::listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )

Golang中有哪些函数具有类似的功能?

谢谢大家。

2 回复

刚刚尝试搜索"golang time countrycode",第一个结果是Stack Overflow上的帖子,看起来您在那里得到了很多回答 😊

stackoverflow.com

如何通过国家代码获取Golang时区

标签: datetime, go, timezone, country-codes

正如Stack Overflow回答中所说,一个国家可能有很多时区,所以从国家代码映射到单个时区基本上是不可能的。我想您可以通过地理位置(如GPS坐标)来获取时区。

更多关于Golang如何根据国家代码获取时区信息的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,可以通过标准库 time 包配合IANA时区数据库来获取特定国家代码的时区信息。虽然Go没有直接等同于PHP DateTimeZone::listIdentifiers 的函数,但可以使用 time.LoadLocation 结合第三方库如 github.com/ringsaturn/tzf 或手动处理时区数据来实现类似功能。

以下是一个使用 time 包和手动映射的示例方法。首先,你需要一个将国家代码映射到IANA时区标识符的数据源。这里使用一个简单的映射示例:

package main

import (
	"fmt"
	"time"
)

// 示例映射:国家代码到IANA时区列表
var countryTimeZones = map[string][]string{
	"US": {"America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles"},
	"GB": {"Europe/London"},
	"JP": {"Asia/Tokyo"},
	"IN": {"Asia/Kolkata"},
	// 添加更多国家代码和时区...
}

// getTimeZonesByCountry 根据国家代码返回时区标识符列表
func getTimeZonesByCountry(countryCode string) ([]string, error) {
	if zones, exists := countryTimeZones[countryCode]; exists {
		return zones, nil
	}
	return nil, fmt.Errorf("no time zones found for country code: %s", countryCode)
}

// 验证时区是否有效
func validateTimeZone(zone string) bool {
	_, err := time.LoadLocation(zone)
	return err == nil
}

func main() {
	countryCode := "US"
	zones, err := getTimeZonesByCountry(countryCode)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Printf("Time zones for country %s:\n", countryCode)
	for _, zone := range zones {
		if validateTimeZone(zone) {
			fmt.Printf("Valid: %s\n", zone)
		} else {
			fmt.Printf("Invalid: %s\n", zone)
		}
	}
}

在这个示例中:

  • countryTimeZones 映射存储了国家代码到IANA时区标识符的列表。
  • getTimeZonesByCountry 函数根据输入的国家代码返回对应的时区列表。
  • validateTimeZone 使用 time.LoadLocation 验证时区标识符是否有效,因为IANA时区必须被系统支持。

对于更全面的实现,建议使用第三方库如 tzf(基于GeoNames数据),它可以自动处理国家代码到时区的映射。安装和使用示例:

go get github.com/ringsaturn/tzf
package main

import (
	"fmt"
	"github.com/ringsaturn/tzf"
)

func main() {
	finder, err := tzf.NewDefaultFinder()
	if err != nil {
		panic(err)
	}

	// 示例:获取美国的所有时区
	countryCode := "US"
	zones := finder.GetTimezonesAtPoint(0, 0) // 注意:此方法基于坐标,需调整以支持国家代码
	// 实际中,你可能需要遍历数据或使用其他方法过滤国家代码
	fmt.Printf("Time zones for %s: %v\n", countryCode, zones)
}

注意:tzf 库主要基于地理坐标查询时区,如果需要直接从国家代码获取,你可能需要预处理数据或查找其他专用库。标准Go库没有内置国家代码到时区的直接映射,因此手动方法或第三方库是常见解决方案。

回到顶部