转换为字符串

基本类型 / 日期和时间

-- 固定的时刻:输出始终相同
local moment = 1798841600

-- "!" 表示 UTC,而 %I 是 12 小时制,
-- %p 是 AM/PM
local short_style =
  os.date("!%m/%d/%y %I:%M %p", moment)
-- short_style = 01/01/27 10:13 PM

local custom_style = os.date("!%Y-%m-%d", moment)
-- custom_style = 2027-01-01

-- %F 即 %Y-%m-%d,而 %T 即 %H:%M:%S
local standard_style = os.date("!%F %T", moment)
-- standard_style = 2027-01-01 22:13:20

-- ISO 8601 格式,日期与时间之间用 "T"
local iso_style = os.date("!%FT%T", moment)
-- iso_style = 2027-01-01T22:13:20

-- %c 是未指定格式时使用的样式
local default_style = os.date("!%c", moment)
-- default_style = Fri Jan  1 22:13:20 2027

-- 嵌入句子中,使用同样的格式代码
local str_format =
  "Today " .. os.date("!%d %B", moment)
-- str_format = Today 01 January

print("short_style = " .. short_style)
print("custom_style = " .. custom_style)
print("standard_style = " .. standard_style)
print("iso_style = " .. iso_style)
print("default_style = " .. default_style)
print("str_format = " .. str_format)

-- 未知的格式代码会报错
local ok, err = pcall(os.date, "%Q", moment)
-- ok = false
-- err = bad argument #1 to 'os.date' (invalid
-- conversion specifier '%Q')
print("ok = " .. tostring(ok))
print("err = " .. err)