关于lua中显示绝对时间和相对时间

来源:互联网 发布:linux 改机器名 编辑:程序博客网 时间:2024/05/16 10:26

最近做公司项目需要把服务器传过来的毫秒数转换为绝对时间如 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)endprint(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 thenminute = math.floor(second / 60)elseminute = nilendif minute and (minute / 60) >= 1 thenhour = math.floor(minute / 60)elsehour = nilendif hour and (hour / 24) >= 1 thenoverhead = math.floor(hour / 24)elseoverhead = nilend--做特殊处理if second >= 60 thensecond = second % 60endif overhead thenhour = hour % 24minute = minute % 60elseif hour thenminute = minute % 60endlocal result = ""if overhead thenif hour ~= 0 thenresult = overhead .. "天" .. hour .. "小时"elseresult = overhead .. "天"endelseif hour thenif minute ~= 0 thenresult = hour .. "小时" .. minute .. "分钟"elseresult = hour .. "小时"endelseif minute thenif second ~= 0 thenresult = minute .. "分钟" .. second .. "秒"-- 这里不需要用秒做单位elseresult = minute .. "分钟"endelseresult = second .. "秒"endreturn resultend



0 0
原创粉丝点击