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))

比如这两个零点日期,通过上述接口计算的dd是非常接近的!

日期 unix timestamp 计算值
2018/8/16 23:59:59 1534435199 17759.66665509259
2018/8/17 00:00:01 1534435201 17759.66667824074

 注意:本内容来自qingqing.zhao's blog

猜你喜欢

转载自blog.csdn.net/xiaochenXIHUA/article/details/92400485