lua 日期与时间操作
2015-05-28 11:03
405 查看
require 'math' require 'os' dateopt = {} dateopt_mt = { __index = dateopt } function dateopt:new() local self = {} setmetatable(self,dateopt_mt) self.year = 1970 self.month = 1 self.day = 1 self.wday = 0 self.hour = 0 self.minute = 0 self.second = 0 return self end function dateopt:init(year,month,day) self.year =year self.month = month self.day = day end function dateopt:subDay(opttime) local _days = 0 local _selfBigger = false if (self.year > opttime.year) then _selfBigger = true elseif (self.year == opttime.year) then if (self.month > opttime.month) then _selfBigger = true elseif (self.month == opttime.month) then if (self.day > opttime.day) then _selfBigger = true elseif (self.day == opttime.day) then return 0 end end end local _bigDate = dateopt:new() local _smallDate =dateopt:new() if _selfBigger == true then _bigDate.year = self.year _bigDate.month = self.month _bigDate.day = self.day _smallDate.year = opttime.year _smallDate.month = opttime.month _smallDate.day = opttime.day else _bigDate.year = opttime.year _bigDate.month =opttime.month _bigDate.day =opttime.day _smallDate.year = self.year _smallDate.month = self.month _smallDate.day = self.day end for _i = _smallDate.year, _bigDate.year-1 do if((_i % 4 == 0 and _i % 100 ~= 0) or _i % 400 == 0) then _days =_days+366 else _days = _days+365 end end for _i = 1,_smallDate.month-1 do if (_i == 1 or _i == 3 or _i == 5 or _i == 7 or _i == 8 or _i == 10 or _i == 12) then _days = _days - 31 elseif (_i == 4 or _i == 6 or _i == 9 or _i == 11) then _days =_days - 30 elseif (_i == 2) then if (_smallDate.year % 4 == 0 and _smallDate.year % 100 ~= 0) or (_smallDate.year % 400 == 0 ) then _days = _days - 29 else _days = _days - 28 end end end _days =_days- _smallDate.day for _i = 1,_bigDate.month-1 do if (_i == 1 or _i == 3 or _i == 5 or _i == 7 or _i == 8 or _i == 10 or _i == 12) then _days =_days+31 elseif (_i == 4 or _i == 6 or _i == 9 or _i == 11) then _days = _days+30 elseif _i == 2 then if ((_bigDate.year % 4 == 0 and _bigDate.year % 100 ~= 0) or _bigDate.year % 400 == 0) then _days =_days+ 29 else _days =_days+28 end end end _days = _days+_bigDate.day return _days end function getCurrentWeekday() local weekday = os.date("%w") return weekday end function getCurrentDate() local year= os.date("%Y") local month =os.date("%m") local day = os.date("%d") return year,month,day end function get1970ToNow_subdays() local Date1 = dateopt:new() local Date2 = dateopt:new() local year =0 local month = 0 local day = 0 local _nDays = 0 year,month,day = getCurrentDate() Date2:init(tonumber(year),tonumber(month),tonumber(day)) _nDays = Date1:subDay(Date2) return _nDays end print(get1970ToNow_subdays()) print(getCurrentWeekday()) print(getCurrentDate())