如果条件比较两个字符串格式HH:MM:SS

时间:2019-02-12 14:47:56

标签: javascript

嗨,我是javascript新手,我想在下面有两个var的地方实现代码 开始时间和结束时间是军事格式

  var start1= 08:00:00
  var endto=03:00:00

我想创建一个条件,如果我的给定时间在start1到结束之间

例如:

giventime = 02:00:00将通过,因为它在08:00:00 - 03:00:00

范围内

giventime = 05:00:00不会通过,因为它不在08:00:00 - 03:00:00范围内

我尝试使用下面的代码:

   var start1= 08:00:00
   var endto=03:00:00
   var giventime = 02:00:00 


if giventime>start1 && giventime<=endto {

//but doesnt work it should allow because 02:00:00 is withing the range of 
  start1 and endto
     }

3 个答案:

答案 0 :(得分:1)

您可以添加给定时间的任何日期,并将其转换为'after save',然后使用Date获得getTime()。现在检查是否miliseconds然后从start > end减去1天

start

答案 1 :(得分:0)

由于格式问题,您将遇到问题。相反,您可以查看可以使用new Date("January 19, 2019 08:00:00")方法完成的包括日期在内的时间。

例如,如果您为开始日期做过if,并且类似地为结束日期做了一个,则可以将Date对象与您的state语句进行比较。

答案 2 :(得分:0)

您需要一个条件来检查开始时间是否大于结束时间。

在这种情况下,您需要检查给定的日期是否大于开始日期小于结束时间。

"02:00:00" > "08:00:00" || "02:00:00" < "03:00:00" // true
"05:00:00" > "08:00:00" || "05:00:00" < "03:00:00" // false

"02:00:00" > "03:00:00" && "02:00:00" < "08:00:00" // false
"05:00:00" > "03:00:00" && "05:00:00" < "08:00:00" // true

function IsInTime(start, end, given)
{
    if (start < end)
    {
        return (given > start && given <= end);
    }
    return (given > start || given <= end);
}

var start1 = "08:00:00"
var endto = "03:00:00"
var giventime = "02:00:00"

if (IsInTime(start1, endto, giventime))
{
    console.log(giventime + " is in the range " + start1 + " - " + endto);
}
else
{
    console.log(giventime + " is NOT in the range " + start1 + " - " + endto);
}

start1 = "08:00:00"
endto = "03:00:00"
giventime = "05:00:00"

if (IsInTime(start1, endto, giventime))
{
    console.log(giventime + " is in the range " + start1 + " - " + endto);
}
else
{
    console.log(giventime + " is NOT in the range " + start1 + " - " + endto);
}

start1 = "03:00:00"
endto = "08:00:00"
giventime = "02:00:00"

if (IsInTime(start1, endto, giventime))
{
    console.log(giventime + " is in the range " + start1 + " - " + endto);
}
else
{
    console.log(giventime + " is NOT in the range " + start1 + " - " + endto);
}

start1 = "03:00:00"
endto = "08:00:00"
giventime = "05:00:00"

if (IsInTime(start1, endto, giventime))
{
    console.log(giventime + " is in the range " + start1 + " - " + endto);
}
else
{
    console.log(giventime + " is NOT in the range " + start1 + " - " + endto);
}