ISO 8601日期时间格式转换为hh:mm - 然后加减分钟

我试图从这个日期格式 2021-09-28T12:00:00-05:00 中提取小时和分钟。对于我的使用,实际的日期和时区不重要。我已经采用了一种简单的方法,就是获取子字符串。

starDate = "2021-09-28T12:00:00-05:00"
print(string.sub(starDate, 12, 16))

过去我已经通过将小时和分钟分别拆分成单独的字符串并从小时和分钟中加减后再将两个字符串拼接在一起来实现这个目的。请原谅我的新手编码...

function OpenMath()
  TriggerMath1 = math.floor(TOS / 60)
  TriggerMath2 = string.format('%d \n' , TOS - TriggerMath1 * 60, '' )
  print(TriggerMath2)
  if OpenM < TriggerMath2 then
    TH = OpenH - (TriggerMath1 + 1)
    TM = OpenM + (60 - TriggerMath2)
   else
    TH = OpenH - TriggerMath1
    TM = OpenM - TriggerMath2
  end
  if TM == 60 then
    TH = TH + 1
    TM = '00'
  end
  TH = string.format('%02d' , TH, '' )
  TM = string.format('%02d' , TM, '' )
  print('OpenMath')
end

有没有更好的方法提取hh:mm作为时间,然后加减分钟呢?

原文链接 https://stackoverflow.com/questions/69365285

点赞
stackoverflow用户2755919
stackoverflow用户2755919

Lua 的日期和时间处理功能在初始状态下相当有限,但在这种情况下,如果您可以使用一个良好一致的输入格式并且不关心时区,我们可以使用标准库中的内容来完成工作。

function stardateToDatetime(stardate)
  local Y,M,D,h,m,s = stardate:match('^(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)')
  return {
    year = tonumber(Y, 10);
    month = tonumber(M, 10);
    day = tonumber(D, 10);
    hour = tonumber(h, 10);
    min = tonumber(m, 10);
    sec = tonumber(s, 10);
  }
end
local dt = stardateToDatetime("2021-09-28T12:00:00-05:00")
print(os.date(nil, os.time(dt))) -- "Tue Sep 28 12:00:00 2021"

这些字段名不是任意的,而是取自 os.date 的文档,这意味着您可以将表传递给 os.time() 以获取系统时间戳,并通过调整字段来处理代表的日期/时间进行数学运算。如果您将它们放在范围之外,那没关系,因为 os.time 会进行修正(例如将 hour=1;min=120 转换为 hour=3;min=0):

dt.min = dt.min + 135 -- 2h15m
print(os.date(nil, os.time(dt))) -- "Tue Sep 28 14:15:00 2021"

如果您需要规范化表格,则可以将其输入 os.time() 来获得系统时间戳,然后将其传递给 os.date() 以获取规范化后的表格:

print(dt.hour, dt.min) -- 12 135
local normalized = os.date('*t', os.time(dt))
print(normalized.hour, normalized.min) -- 14 15

更多详细信息请参见:

  • os.date -- 将系统时间戳转换为表格或可读字符串
  • os.time -- 从系统时钟或日期时间表获取系统时间戳
  • string.match -- 类似于正则表达式的字符串匹配和子组提取
2021-09-30 15:20:11