【问题标题】:Lua UTC time inconsistenciesLua UTC 时间不一致
【发布时间】:2015-02-06 01:25:43
【问题描述】:

Lua 5.1 文档说:

如果格式以 '!' 开头,则日期格式为 Coordinated 世界时。

如果格式是%c! 的行为似乎是正确的

local date_1 = os.date("!%c")
local date_2 = os.date("%c")
print("utc date: "..date_1)
print("not utc date: "..date_2)

如果格式为*t! 的行为似乎已交换

local time_1 = os.time(os.date("!*t"))
local time_2 = os.time(os.date("*t"))
print("should be utc time, but is not: "..time_1) -- this should be UTC, and is not
print("should not be utc time, but is: "..time_2) -- this should not be UTC, but is

测试日期:http://www.epochconverter.com/

为什么会这样?

【问题讨论】:

    标签: time lua utc


    【解决方案1】:

    os.date("!*t")os.date("*t") 返回的表是正确的。我只打印hour 字段。注意它们与%c格式一致:

    local date_1 = os.date("!%c")
    local date_2 = os.date("%c")
    print("utc date: "..date_1)
    print("not utc date: "..date_2)
    
    print("utc date hour: " .. os.date("!*t").hour)
    print("not utc date hour: " .. os.date("*t").hour)
    

    我机器上的输出(中国标准时间,UTC+08:00):

    utc date: 02/06/15 02:02:29
    not utc date: 02/06/15 10:02:29
    utc date hour: 2
    not utc date hour: 10
    

    但是,os.time 获取表格,假设它是当地时间,并返回纪元。因此,本地时间被转换为真正的纪元,但UTC时间不是。

    print(os.time{year=1970, month=1, day=1, hour=8})
    

    在我的机器上输出0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      • 2013-09-29
      相关资源
      最近更新 更多