首页 > 代码库 > Lua 仿PHP的strtotime

Lua 仿PHP的strtotime

 由于工作原因,两周前开始研究Lua,因为之前的项目要由php改成Lua实现,而一些php里现成的东西,在Lua里就需要手写,于是就有了下面的代码。写的比较粗糙,权当做个记录吧。

--[[获取时间戳--]]function strtotimestamp(timeToConvert)    local ymdhis = "(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)"    local runyear,runmonth,runday = getymd(timeToConvert);    local runhour,runminute,runseconds = gethis(timeToConvert);    local convertedTimestamp = os.time({                                           year = runyear,                                           month = runmonth,                                           day = runday,                                           hour = runhour,                                           min = runminute,                                           sec = runseconds                                       });    return convertedTimestamp;end--[[获取年、月、日--]]function getymd(str)    local ymd =  "(%d+)-(%d+)-(%d+)"    local md =  "(%d+)-(%d+)"    local runyear, runmonth, runday = str:match(ymd);    if runyear then        return runyear, runmonth, runday;    else        local runmonth, runday = str:match(md);        if runmonth then             return nil,runmonth, runday;        else            return nil,nil,nil;        end    endend--[[获取时、分、秒--]]function gethis(str)    local his = "(%d+):(%d+):(%d+)"    local hi = "(%d+):(%d+)"    local runhour, runminute, runseconds = str:match(his);    if runhour then        return runhour, runminute, runseconds;    else        local runhour, runminute = str:match(hi);        if runhour then             return runhour, runminute, nil;        else            return nil,nil, nil;        end    endend