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

时间:2017-07-06 21:28:28

标签: 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     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

或者甚至以下内容应该可以删除os.time()

local function BetweenTimes(between, start, stop)
   local start   = string.gsub(start,":", "")
   local between = string.gsub(between,":", "") 
   local stop    = string.gsub(stop,":", "") 

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

2 个答案:

答案 0 :(得分:2)

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

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
      stop = stop + 24*60*60 -- add 24 h
   end
   return (start <= between) and (between <= stop)
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

答案 1 :(得分:1)

为什么你只有几小时和几分钟才使用日期?除非您希望将来处理任何其他时间单位,否则简单的乘法就足够了。

local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return min * 60 + hour
end

我不会从Henri Menke的回答中复制BetweenTimes - 它与包装处理中唯一的变化完全相同,因为我的parse_time会返回分钟,而不是秒:

stop = stop + 24*60