Lua date转秒数

之前写过一篇关于把秒转换成指定的日期格式 Lua date format

 

接到一个需求,需要从配置文件中读取活动显示时间段:startDate ~ endDate(格式为:yyyy-mm-dd HH:MM:SS),然后与服务器返回的时间进行比较,如果在该时间段内则显示该活动,如何实现呢?

 

首先我们借助“split”函数来获得相应的年、月、日、时、分、秒,然后将其转换为秒再比较

-- Compatibility: Lua-5.1
function split(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end

---- 通过日期获取秒 yyyy-MM-dd HH:mm:ss
function GetTimeByDate(r)
local a = split(r, " ")
local b = split(a[1], "-")
local c = split(a[2], ":")
local t = os.time({year=b[1],month=b[2],day=b[3], hour=c[1], min=c[2], sec=c[3]})

return t
end

默认Lua的time函数返回的是秒数,延伸阅读 Date and Time >>
posted @ 2013-10-24 15:46  meteoric_cry  阅读(9605)  评论(2编辑  收藏  举报