Lua-计算时间是否在两个时间戳之间

Lua-计算时间是否在两个时间戳之间,lua,Lua,举以下例子: --Test current start end between --1 10:00 09:00 12:00 true --2 01:00 07:34 09:54 false --3 17:00 16:00 03:00 true --4 10:00 10:00 15:00 true --5 10:30 10:00

举以下例子:

--Test current     start     end     between
--1    10:00       09:00     12:00   true
--2    01:00       07:34     09:54   false
--3    17:00       16:00     03:00   true
--4    10:00       10:00     15:00   true
--5    10:30       10:00     10:30   true
在Lua中,如何最好地创建我可以调用的函数:

BetweenTimes ("10:00", "09:00","12:00")
在这种情况下(测试1)返回true。我的问题是将测试用例3

我可以假设第一次总是在第二次之前

我想可能是这样的:

local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return os.time{hour = hour, min = min, day = 1, month = 1, year = 1970}
end

local function BetweenTimes(between, start, stop)
   between = parse_time(between)
   start   = parse_time(start)
   stop    = parse_time(stop)

   if stop < start then
      return (start <= between) or (between <= stop)
   else
      return (start <= between) and (between <= stop)
   end
end

print(BetweenTimes("10:00", "09:00", "12:00")) -- true
print(BetweenTimes("15:00", "09:00", "12:00")) -- false
print(BetweenTimes("15:00", "09:00", "01:00")) -- true
print(BetweenTimes("10:00", "10:00", "11:00")) -- true
print(BetweenTimes("11:00", "10:00", "11:00")) -- true
print(BetweenTimes("19:00", "17:00", "03:30")) -- true
print(BetweenTimes("03:00", "04:00", "05:30")) -- false
print(BetweenTimes("03:00", "02:00", "05:30")) -- true
print(BetweenTimes("01:00", "09:00", "02:30")) -- true

你的方法听起来太复杂了。只需解析字符串中的小时和分钟,并将其转换为UNIX时间戳。这些是常规整数,您可以使用
轻松比较它们

本地函数解析时间(str)
本地小时,min=str:match((%d+):(%d+))
返回os.time{hour=hour,min=min,day=1,month=1,year=1970}
结束
间隔时间(间隔、启动、停止)的本地功能
between=解析时间(between)
开始=解析时间(开始)
停止=解析时间(停止)
如果停止<开始,则
停止=停止+24*60*60——加上24小时
结束

return(start为什么在只有小时和分钟的情况下还要使用日期?除非您希望将来处理任何其他时间单位,否则简单的乘法就足够了

local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return min * 60 + hour
end
我不会从Henri Menke的答案中复制
interweentimes
——这与包装处理中唯一的更改完全相同,因为我的
parse_time
返回的是分钟,而不是秒:

stop = stop + 24*60

感谢您的回复。这个案例如何:
print(在时间间隔(“15:00”、“09:00”、“01:00”))
我想让它返回真值,因为15:00是在上午9点到凌晨1点之间,其中开始时间>=停止时间。@HelpingHand什么?15:00肯定不是在01:00到09:00之间。至少不是在同一天。@HelpingHand我添加了24小时包装,如果
停止
开始
之前。谢谢你的帮助。它通过了所有的测试用例我都有。我对需要做什么有一个粗略的想法。我很想听听更熟悉LUA的人关于正确/最简单的方法。再次感谢。@helpingh,我将把这个作为练习留给你;)我相信你能弄明白。Does
在时间间隔(“01:00”,“09:00”,“02:00”)
return true?@lhf感谢您指出这一点,当它应该返回true时,它确实返回false。
local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return min * 60 + hour
end
stop = stop + 24*60