LUA 比較兩個時間點(os.date())之間的時間間隔值
阿新 • • 發佈:2019-01-09
--[[比較兩個時間,返回相差多少時間]] function timediff(long_time,short_time) local n_short_time,n_long_time,carry,diff = os.date('*t',short_time),os.date('*t',long_time),false,{} local colMax = {60,60,24,os.date('*t',os.time{year=n_short_time.year,month=n_short_time.month+1,day=0}).day,12,0} n_long_time.hour = n_long_time.hour - (n_long_time.isdst and 1 or 0) + (n_short_time.isdst and 1 or 0) -- handle dst for i,v in ipairs({'sec','min','hour','day','month','year'}) do diff[v] = n_long_time[v] - n_short_time[v] + (carry and -1 or 0) carry = diff[v] < 0 if carry then diff[v] = diff[v] + colMax[i] end end return diff end local n_long_time = os.date(os.time{year=2014,month=6,day=10,hour=16,min=0,sec=0}); local n_short_time = os.date(os.time{year=2013,month=5,day=11,hour=16,min=0,sec=0}); local t_time = timediff(n_long_time,n_short_time); local time_txt = string.format("%04d", t_time.year).."年"..string.format("%02d", t_time.month).."月"..string.format("%02d", t_time.day).."日 "..string.format("%02d", t_time.hour)..":"..string.format("%02d", t_time.min)..":"..string.format("%02d", t_time.sec); print(time_txt);