介紹lua的日期函數常用方法及我的一個踩坑。
時間戳轉日期
os.date("%Y%m%d%H",unixtime)
--os.date("%Y%m%d%H",1534435200) 2018081700
日期轉時間戳
---指定日期的時間戳
os.time({day=17, month=8, year=2018, hour=0, minute=0, second=0})
--1534435200
當前時間戳
os.time()
格式占位符
--時間格式 yyyyMMddHHmmss
print(os.date("%Y-%m-%d %H:%M %S", os.time()))
---輸出 2019-01-30 10:47 53
print(os.date("%m月%d日 %H:%M", os.time())) --輸出 01月30日 10:44
轉成年月日接口
function Tool.FormatUnixTime2Date(unixTime)
if unixTime and unixTime >= 0 then
local tb = {}
tb.year = tonumber(os.date("%Y",unixTime))
tb.month =tonumber(os.date("%m",unixTime))
tb.day = tonumber(os.date("%d",unixTime))
tb.hour = tonumber(os.date("%H",unixTime))
tb.minute = tonumber(os.date("%M",unixTime))
tb.second = tonumber(os.date("%S",unixTime))
return tb
end
end
當然,如果你只需要拿天數進行比較,可以使用tonumber(os.date("%d",unixTime))
踩坑日志
不建議采用以下方式計算日期
function Tool.FormatDiffUnixTime2Tb(diffUnixTime)
if diffUnixTime and diffUnixTime >= 0 then
local tb = {}
---一天的秒數86400
tb.dd = math.floor(diffUnixTime / 60 / 60 / 24)
tb.hh = math.floor(diffUnixTime / 3600) % 24
tb.mm = math.floor(diffUnixTime / 60) % 60
tb.ss = math.floor(diffUnixTime % 60)
return tb
end
end
比如這兩個零點日期,通過上述接口計算的dd是非常接近的!
日期 | unix timestamp | 計算值 |
---|---|---|
2018/8/16 23:59:59 | 1534435199 | 17759.66665509259 |
2018/8/17 00:00:01 | 1534435201 | 17759.66667824074 |
轉換計算工具
時間戳轉換:http://tool.chinaz.com/Tools/unixtime.aspx
秒轉成時間:http://cn.bestconverter.org/unitconverter_time.php
參考資料
https://www.cnblogs.com/Denny_Yang/p/6197435.html
http://www.cnblogs.com/whiteyun/archive/2009/08/10/1542913.html