最近做公司项目需要把服务器传过来的毫秒数转换为绝对时间如 2016年4月6日09:55:45
或者相对时间1年3个月\3个月15天\15天11小时\11小时13分
绝对时间直接用lua os库
-- 时间转换
local function transformationDate(ms)
local date = os.date("*t", ms / 1000)
return string.format("%d年%d月%d日 %d时%d分%d秒", date.year, date.month, date.day, date.hour, date.min, date.sec)
end
print(transformationDate(485182870))
相对时间自己写的函数 略复杂
有能力的朋友 可以自己精简
-- 该函数单位上线为天 最大以天为单位 最小返回0秒 最多只显示2个单位 如果显示 1天 1分钟 只显示1天 中间单位会被抛弃
function getValidTime(millisecond) -- 参数毫秒
local second = millisecond / 1000 -- 转化为秒
local minute = nil -- 分钟
local hour = nil -- 小时
local overhead = nil -- 天
if second and (second / 60) >= 1 then
minute = math.floor(second / 60)
else
minute = nil
end
if minute and (minute / 60) >= 1 then
hour = math.floor(minute / 60)
else
hour = nil
end
if hour and (hour / 24) >= 1 then
overhead = math.floor(hour / 24)
else
overhead = nil
end
--做特殊处理
if second >= 60 then
second = second % 60
end
if overhead then
hour = hour % 24
minute = minute % 60
elseif hour then
minute = minute % 60
end
local result = ""
if overhead then
if hour ~= 0 then
result = overhead .. "天" .. hour .. "小时"
else
result = overhead .. "天"
end
elseif hour then
if minute ~= 0 then
result = hour .. "小时" .. minute .. "分钟"
else
result = hour .. "小时"
end
elseif minute then
if second ~= 0 then
result = minute .. "分钟" .. second .. "秒" -- 这里不需要用秒做单位
else
result = minute .. "分钟"
end
else
result = second .. "秒"
end
return result
end