lua时间戳和日期转换及踩坑

介绍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()))

转成年月日接口

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:59153443519917759.66665509259
2018/8/17 00:00:01153443520117759.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

http://blog.csdn.net/goodai007/article/details/8077285

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值