【问题标题】:How to get current system Time Zone by using Lua如何使用 Lua 获取当前系统时区
【发布时间】:2019-03-26 04:45:21
【问题描述】:

如何使用 Lua 获取当前系统的时区。 (美国/山区)。我正在研究 Linux 操作系统。我需要知道如何获得像 (US/Mountain, Asia/Mumbai) 这样的 Linux 系统。如何为此编写代码

【问题讨论】:

    标签: lua lua-table


    【解决方案1】:

    你可以使用 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()
    • 时区名称,没有。 偏移量和缩写,是的
    【解决方案2】:

    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
    

    资源:lua-users: Time Zone

    【讨论】:

    • 您获得该日期时间格式的语言环境是什么?
    • 你指的是答案的第一行吗?我说西雅图,我可以更清楚地说明美国华盛顿州西雅图。
    • 我很惊讶你得到了这种日期格式。我得到Mon Mar 25 15:51:05 2019 -0400%c 输出取决于区域设置。 locale | grep LC_TIME 输出 LC_TIME=en_CA.utf-8locale date_fmt 输出 %a %b %e %H:%M:%S %Z %Y -- 你的输出是什么?
    • @glennjackman %c 不应依赖于语言环境。它在lua.org/pil/22.1.html上记录为%c date and time (e.g., 09/16/98 23:48:10)
    • @glennjackman 我在 Windows 机器上,所以我的日期格式短日期 = M/d/yyyy 和我的时间格式长时间 = h:mm:ss tt
    猜你喜欢
    • 2011-07-02
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2016-09-11
    • 2013-01-27
    相关资源
    最近更新 更多