【发布时间】:2019-03-26 04:45:21
【问题描述】:
如何使用 Lua 获取当前系统的时区。 (美国/山区)。我正在研究 Linux 操作系统。我需要知道如何获得像 (US/Mountain, Asia/Mumbai) 这样的 Linux 系统。如何为此编写代码
【问题讨论】:
如何使用 Lua 获取当前系统的时区。 (美国/山区)。我正在研究 Linux 操作系统。我需要知道如何获得像 (US/Mountain, Asia/Mumbai) 这样的 Linux 系统。如何为此编写代码
【问题讨论】:
你可以使用 luarocks luatz 包:
$ luarocks install luatz
然后
> luatz = require("luatz")
> now = luatz.time()
> new_york = luatz.time_in('America/New_York', now)
> print(luatz.timetable.new_from_timestamp(new_york))
2019-03-25T16:19:43.696
> paris = luatz.time_in('Europe/Paris', now)
> print(luatz.timetable.new_from_timestamp(paris))
2019-03-25T21:19:43.696
该库具有有限的功能来返回有关时区本身的信息:
> america_new_york = luatz.get_tz('America/New_York')
> for key,val in pairs(america_new_york:find_current(now)) do print(key,val) end
abbrind 4
isstd false
isdst true
isgmt false
gmtoff -14400
abbr EDT
> europe_paris = luatz.get_tz('Europe/Paris')
> for key,val in pairs(europe_paris:find_current(now)) do print(key,val) end
abbrind 17
isstd true
isdst false
isgmt true
gmtoff 3600
abbr CET
要查询当前系统时区,请使用不带参数的luatz.get_tz()。我没有看到任何获取 Olson 时区名称的方法,但您可以获得一些数据
> now = luatz.time()
> mytz = luatz.get_tz()
> mytz_info = mytz:find_current(now)
> mytz_info.abbr
EDT
> mytz_info.gmtoff
-14400
> mytz_info.isdst
true
【讨论】:
get_tz()?
print( os.date('%m/%d/%y %H:%M:%S %z',t0)) = 03/25/19 10:57:29 Pacific Daylight Time 我在美国华盛顿州西雅图市。
%z 为您提供时区,这可能足以满足您的需求,但请注意:
不能使用 os.date("%z") 因为它的返回值格式是不可移植的;特别是,Windows 系统不使用 strftime() 的 C99 语义。 - http://lua-users.org/wiki/TimeZone
或者,您可以执行以下操作来确定偏移量的实际值:
local function get_timezone_offset(ts)
local utcdate = os.date("!*t", ts)
local localdate = os.date("*t", ts)
localdate.isdst = false -- this is the trick
return os.difftime(os.time(localdate), os.time(utcdate))
end
【讨论】:
Mon Mar 25 15:51:05 2019 -0400。 %c 输出取决于区域设置。 locale | grep LC_TIME 输出 LC_TIME=en_CA.utf-8 和 locale date_fmt 输出 %a %b %e %H:%M:%S %Z %Y -- 你的输出是什么?
%c 不应依赖于语言环境。它在lua.org/pil/22.1.html上记录为%c date and time (e.g., 09/16/98 23:48:10)
M/d/yyyy 和我的时间格式长时间 = h:mm:ss tt