lua - 如何在 Lua 中以格式化字符串的形式获取本地时间

标签 lua datetime-format

我需要一个格式为 %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
来自 os.date 上的 Lua 5.3 手册:

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

关于lua - 如何在 Lua 中以格式化字符串的形式获取本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55472873/

相关文章:

ios - 使用 LUA 的 Cocos2dx iOS 项目

python - 如何从Python调用Lua函数?

networking - 将数据包信息写入文本文件

tsql - 如何在 SQL Server 中将 DateTime 字符串转换为 DateTime

java - DateTimeFormatter 创建模式

java - Zulu 和 Offset 的日期时间格式

c - 在 Lua 中注册相同签名的 C 函数

javascript - RFC 2822 和 ISO 8601 日期格式正则表达式

asp.net - 指定 WCF 数据服务的日期时间格式

c - 执行应用程序时找不到 libuuid 库,尽管它可以完美编译