如何在 Lua 中获取本地时间作为格式化字符串

How to get local time as a formatted string in Lua

我需要一个格式为 %Y-%m-%d %H:%M:%S.

的日期时间字符串

我不知道如何使用 Lua 的标准函数 os.date()os.time() 来实现。

os.date 是您要查找的函数。它的第一个可选参数 format 做你想做的事:

os.date('%Y-%m-%d %H:%M:%S')
--> 2019-04-02 10:50:52

来自 Lua 5.3 手册 os.date

os.date ([format [, time]])

Returns a string or a table containing date and time, formatted according to the given string format.

If format starts with '!', then the date is formatted in Coordinated Universal Time.

If format is not "*t", then date returns the date as a string, formatted according to the same rules as the ISO C function strftime.

你可以详细了解C的格式化规则strftime here.

如果您出于某种原因得不到本地时间,您可以简单地添加所需的偏移量。

local timeShift = 3 * 60 * 60  -- +3 hours
os.date('%Y-%m-%d %H:%M:%S', os.time() + timeShift)
--> 2019-04-02 18:24:15 for 15:24:15 UTC

我使用库https://github.com/Tieske/date。获取当地时间 -

date(true):addminutes("your offset"):fmt('%Y-%m-%d %H:%M:%S'),