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

我正在创建一个管理工具,需要将类似于 '1y2m3d4h5mi6s' 的字符串类型转换为 Lua 中的 Unix 时间(以秒为单位)。我该怎么做?

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

点赞
用户10126088
用户10126088

将日期字符串转换成秒数的代码片段

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)
2019-02-08 15:48:42
用户6834680
用户6834680
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
将时间字符串转换成秒数

使用 Lua 编写一个函数,将如下格式的时间字符串转换成秒数:

1d   -- 表示 1 天 或 86400 秒
1h   -- 表示 1 小时 或 3600 秒
1m   -- 表示 1 分钟 或 60 秒
1s   -- 表示 1 秒
格式示例:
2d1h30m10s   -- 表示 2 天 1 小时 30 分钟 10 秒,总共 179410 秒

解题思路:
先将字符串分割出数字和单位,再依次加上对应时间段的秒数即可。
2019-02-08 16:27:53