在Lua中获取UTC UNIX时间戳

时间:2017-05-08 20:59:37

标签: datetime time lua timestamp strftime

API返回时间戳作为UTC时间戳的UNIX时间戳,我想知道此时间戳是否超过x秒前。正如预期的那样,这与UTC中的os.time() - x > timestamp一起工作正常,但在其他时区爆炸。

不幸的是,我无法在lua中找到解决这个问题的好方法。

os.date有助于!前缀(例如os.date("!%H:%M:%S"))以返回UTC的时间,但似乎尽管文档声明它支持所有strftime选项,不支持%s选项。我听说有人提到这是由类似问题的Lua编译时选项引起的,但由于解释器是由用户提供的,因此无法更改这些选项。

2 个答案:

答案 0 :(得分:8)

您可以使用

os.time(os.date("!*t"))

获取当前的UNIX纪元。

答案 1 :(得分:2)

好,所以你想要UTC时间。请记住,os.time实际上是 knows nothing about timezones ,例如:

os.time(os.date("!*t"))
  1. 将获得UTC时间并填充表结构。
  2. 将根据当前时区将表结构转换为unix时间戳。

因此,您实际上将获得UNIX_TIME-TIMEZONE_OFFSET。如果您使用的是格林尼治标准时间+5,您将在UTC-5获得时间戳。

在lua中进行时间转换的正确方法是:

os.time() - get current epoch value
os.time{ ... } - get epoch value for local date/time values
os.date("*t"),os.date("%format") - get your local date/time
os.date("!*t") or os.date("!%format") - get UTC date/time
os.date("*t", timestamp),os.date("%format", timestamp) - get your local date/time for given timestamp
os.date("!*t", timestamp) or os.date("!%format", timestamp) - get UTC date/time for given timestamp

Monshttps://gist.github.com/ichramm/5674287表示敬意。

如果您确实需要将任何UTC日期转换为时间戳,则在此问题中有一个很好的说明:Convert a string date to a timestamp

相关问题