(原创)lua日期、时间、时间戳的计算和转换

----------------------------------------------日期与时间
print("当前时间戳:")
local nowTime = os.time()
print(nowTime)

print("")
print("转换成日期:")
--时间戳 转 日期
local nowData = os.date("%Y%m%d%H%M%S",nowTime)
print(nowData)

--可以单独转换
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))

--转成table
local tb = os.date("*t",nowTime)
dump(tb)

print("")
print("日期转回时间戳:")
print(os.time(tb))



print("")

local time1 = os.time({year=2018,month=2,day=28,hour=23, min=0, sec=3})
local time2 = os.time({year=2018,month=3,day=1,hour=1, min=0, sec=2})


print("获取时间戳对应的日期")
--获取时间戳对应的天数(天数规则不是自然天,是(hour)4点前当前一天算)
function Tool:GetDayKeyByUnixTime(unixTime,hour)
    if hour == nil then hour = 0 end
    local retStr = os.date("%Y-%m-%d %H:%M:%S",unixTime)
    local time = unixTime
    local data = os.date("*t",time)
    --dump(data)

    --(hour)4点前按前一天算
    if data.hour < hour then
        time = time - 24*60*60        
    end

    local data2 = os.date("*t",time)
    --dump(data2)
    data2.hour = 0
    data2.min = 0
    data2.sec = 0

    local time2 = os.time(data2)

    local dayKey = os.date("Key%Y%m%d",time2)
    local timeBase = time2

    --天数key,日期格式字符串,天数key 0点的时间戳
    return dayKey,retStr,timeBase
end

local dayKey,str = Tool:GetDayKeyByUnixTime(time1,4)
print("dayKey = "..dayKey.."  str = "..str)
dayKey,str = Tool:GetDayKeyByUnixTime(time2,4)
print("dayKey = "..dayKey.."  str = "..str)


--两个时间的天数差              --时间戳1  时间戳2  多少点开始算第二天
function Tool:NumberOfDaysInterval(unixTime1,unixTime2,dayFlagHour)
    if dayFlagHour == nil then dayFlagHour = 0 end
    local key1,str1,time1 = Tool:GetDayKeyByUnixTime(unixTime1,dayFlagHour)
    local key2,str2,time2 = Tool:GetDayKeyByUnixTime(unixTime2,dayFlagHour)

    local sub = math.abs(time2 - time1)/(24*60*60)
    print(str1..""..str2.."相差的天数:"..sub)

    return sub
end

local sub = Tool:NumberOfDaysInterval(time1,time2,4)
print(sub)

 

posted @ 2018-12-19 18:16  冥府骑士格斯  阅读(9099)  评论(0编辑  收藏  举报