在Lua中获取UTC UNIX时间戳

Azs*_*sgy 11 time lua datetime timestamp strftime

API返回一个时间戳作为UTC时间戳的UNIX时间戳,我想知道这个时间戳是否超过x几秒钟.正如预期的那样,这os.time() - x > timestamp在UTC中运行良好,但在其他时区爆炸.

不幸的是我找不到一个好方法来解决这个问题.

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

Joe*_*Joe 10

您可以使用

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

获得当前的UNIX时代.

  • 事实上,它在我的系统上失败了。linux `date` 返回 14:40,`date -u` 返回 12:40,但是 lua `os.time(os.date("!*t"))` 返回 1562240400 对应于 13:40,所以看起来存在时区/夏令时问题 (3认同)
  • 关于性能的注意事项:这比采用os.time()并减去差异大约慢500倍.但是因为我预计这种方法存在错误,并且预计最大消息/秒将在200左右,我将继续这样做. (2认同)

kwo*_*orr 5

好的,所以你想要 UTC 时间。请记住,os.time实际上对 timezones 一无所知,例如:

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

所以你实际上会得到你的 UNIX_TIME - TIMEZONE_OFFSET。如果您在 GMT+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
Run Code Online (Sandbox Code Playgroud)

https://gist.github.com/ichramm/5674287 上Mons致敬

如果您确实需要将任何 UTC 日期转换为时间戳,那么在这个问题中有一个关于如何执行此操作的很好的描述:Convert a string date to a timestamp