如何将字符串时间转换为Unix?

时间:2019-02-08 14:27:36

标签: lua

我正在创建一个管理工具,我需要在Lua中将字符串类型转换为:“ 1y2m3d4h5mi6s”为unixtime(秒)。我该怎么做?

我希望StrToTime("1d")的输出为86400

2 个答案:

答案 0 :(得分:4)

function StrToTime(time_as_string)
   local dt = {year = 2000, month = 1, day = 1, hour = 0, min = 0, sec = 0}
   local time0 = os.time(dt)
   local units = {y="year", m="month", d="day", h="hour", mi="min", s="sec", w="7day"}
   for num, unit in time_as_string:gmatch"(%d+)(%a+)" do
      local factor, field = units[unit]:match"^(%d*)(%a+)$"
      dt[field] = dt[field] + tonumber(num) * (tonumber(factor) or 1)
   end
   return os.time(dt) - time0
end

print(StrToTime("1d"))      --  86400
print(StrToTime("1d1s"))    --  86401
print(StrToTime("1w1d1s"))  --  691201
print(StrToTime("1w1d"))    --  691200

答案 1 :(得分:2)

将您的日期字符串转换为秒的代码段

local testDate = '2019y2m8d15h0mi42s'
local seconds = string.gsub(
  testDate,
  '(%d+)y(%d+)m(%d+)d(%d+)h(%d+)mi(%d+)s',
  function(y, mon, d, h, min, s)
    return os.time{
      year = tonumber(y),
      month = tonumber(mon),
      day = tonumber(d),
      hour = tonumber(h),
      min = tonumber(min),
      sec = tonumber(s)
    }
  end
)
print(seconds)

您还可以编写一个局部函数,我认为阅读起来会更好一些。

local function printTime(y, mon, d, h, min, s)
  local res = os.time{
    year = tonumber(y),
    month = tonumber(mon),
    day = tonumber(d),
    hour = tonumber(h),
    min = tonumber(min),
    sec = tonumber(s)
  }
  return res
end

local testDate = '2019y2m8d15h0mi42s'
local seconds = string.gsub(
  testDate,
  '(%d+)y(%d+)m(%d+)d(%d+)h(%d+)mi(%d+)s',
  printTime
)
print(seconds)