Origin

Origin

马上订阅 Origin RSS 更新: https://blog.singee.me/atom.xml

谈谈时区

2023年8月20日 14:52

通常在本地化时往往会涉及到时区转换的问题,而通常在真正关注到时区之前我们所「默认」使用的时区为 UTC 或“本地”。

本文以 Go 为例,分析下 Go 中的时区使用。

读取时区

在 Go 中,读取时区使用的是 LoadLocation 函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// LoadLocation returns the Location with the given name.
//
// If the name is "" or "UTC", LoadLocation returns UTC.
// If the name is "Local", LoadLocation returns Local.
//
// Otherwise, the name is taken to be a location name corresponding to a file
// in the IANA Time Zone database, such as "America/New_York".
//
// LoadLocation looks for the IANA Time Zone database in the following
// locations in order:
//
// - the directory or uncompressed zip file named by the ZONEINFO environment variable
// - on a Unix system, the system standard installation location
// - $GOROOT/lib/time/zoneinfo.zip
// - the time/tzdata package, if it was imported
func LoadLocation(name string) (*Location, error)

阅读注释可知,如果 name 为空 / UTC 则使用 UTC、为 Local 则使用本地时区(在后面进行讲解),否则,从特定位置进行读取。

所谓读取,是读取的 tzfile 时区文件,可阅读该文档查阅更多信息。简单来说,时区文件是一个以 TZif 开头的二进制文件,其中包含了时区的偏移量、闰秒、夏令时等信息,Go 可以读取相关文件并解析。

  1. 如果存在 ZONEINFO 环境变量,利用该变量指向的目录/压缩文件进行读取
  2. 在 Unix 系统上,使用系统标准位置
  3. (主要用于编译 Go 时)从 $GOROOT/lib/time/zoneinfo.zip 进行读取
  4. (如果 import 了 time/tzdata )从程序嵌入的数据读取

我们比较关注的是 2,即 Unix 的标准时区文件的存储位置。在 Unix 系系统中,时区文件通常存储在 /usr/share/zoneinfo/ 目录中(根据系统不同,还可能是 /usr/share/lib/zoneinfo/ 或 /usr/lib/locale/TZ/),例如,中国(Asia/Shanghai)的时区定义文件就是 /usr/share/zoneinfo/Asia/Shanghai。因此,通常程序可以直接从系统中获取到时区的信息。

注意,在 alpine 环境中,是没有时区定义文件的,因此我们需要特别关注进行处理

  1. 可以在程序中使用...

剩余内容已隐藏

查看完整文章以阅读更多