如何字符串时间转换为UNIX?

问题描述 投票:3回答:2

我创建一个管理的探讨工具,我需要字符串类型转换这样的:“1y2m3d4h5mi6s”以在Lua unixtime(秒)。我怎样才能让这个?

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

lua
2个回答
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

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)
© www.soinside.com 2019 - 2024. All rights reserved.