萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Lua 時間格式轉換實用函數集

1. 秒數轉 天/時/分/秒

function convertTimeForm(seconds)
    local day = math.floor(seconds / 86400)
    local hour = math.fmod(math.floor(seconds / 3600), 24)
    local min = math.fmod(math.floor(seconds / 60), 60)
    local sec = math.fmod(seconds, 60)
    return day, hour, min, sec
end

-- 用法
local d, h, m, s = convertTimeForm(100000)
print(string.format("%d天 %d時 %d分 %d秒", d, h, m, s))

2. 秒數轉 時:分:秒 (不含天)

function formatTime(seconds)
    local hour = math.floor(seconds / 3600)
    local min = math.fmod(math.floor(seconds / 60), 60)
    local sec = math.fmod(seconds, 60)
    return string.format("%02d:%02d:%02d", hour, min, sec)
end

print(formatTime(3661)) -- 01:01:01

3. 毫秒時間戳轉日期字符串

-- endTime 為毫秒級時間戳
local datetime = os.date("%Y-%m-%d %H:%M", math.floor(endTime / 1000))
print(datetime) -- 2024-01-15 14:30

補充:常用日期格式符

  • %Y 年(4位) %m 月 %d 日
  • %H 時(24制) %M 分 %S 秒
  • %w 星期(0-6, 0為周日)
copyright © 萬盛學電腦網 all rights reserved