当 TZ=":/etc/localtime" 时获取本地时间的正确方法是什么?

What's the proper way to get a local time when TZ=":/etc/localtime"?

我的环境变量 TZ 设置为 :/etc/localtime。文件 /etc/localtime 是文件 /usr/share/zoneinfo/America/Chicago 的符号 link。到目前为止,我正在使用它来获取本地时间对象:

Time.local(
  Crystal::System::Time.load_localtime.not_nil!
) 
# 2019-07-16 20:46:50 -05:00

因为下面的时间设置为 UTC:

Time.local   # 2019-07-17 01:46:50 UTC

Crystal 标准库是否应该 return TZ=":/etc/localtime" 的 UTC 位置,或者我是否应该手动将 TZ 设置为时区(例如 "America/Chicago")?

Time::Location 仅支持 TZ 的值,这些值是相对于 zoneinfo 数据库的路径(例如:America/Chicago)。它目前无法解析绝对路径。不过,这可以作为功能请求添加。

Time.local 给你一个 UTC 的时间只是因为 Time::Location.load_local 无法理解 ENV["TZ"] 的值并且默认为 UTC。如果您简单地取消设置 TZ,它应该会按预期工作。

不设置TZ时,默认为/etc/localtime引用的值。因此,根本不需要您的定制工作。特别是 Crystal::System::Time 不应该直接从用户代码调用。