如果声明只考虑每小时

时间:2015-05-10 13:51:32

标签: javascript jquery

我如何让if statement评估整个时间段,例如,从06:00:00到11:00:00,而不是现在正在做的事情,其中它错过了像06:15:00的时间:

if (time == "6am - 11am") {
    if (rideshareTime == "06:00:00" || rideshareTime == "07:00:00" || rideshareTime == "07:00:00" || rideshareTime == "08:00:00" || rideshareTime == "09:00:00" || rideshareTime == "10:00:00" || rideshareTime == "11:00:00") {
        if (luggageSpace == "Yes") {
            if (rideshareSeats >= seatsAvailable && luggageSpace == rideshareLuggage && womenOnly == rideshareWomen) {
                $obj.closest('.rideshare-item').show();
            }
        } else {
            if (rideshareSeats >= seatsAvailable && womenOnly == rideshareWomen) {
                $obj.closest('.rideshare-item').show();
            }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

我建议使用像momentjs.com这样的日期/时间库及其isBetween方法。

您可以使用字符串数据类型及其substring方法来解决它。虽然我不推荐它,因为字符串不能在日期/时间运行。

if (rideshareTime.substring(0,2) == "06" || rideshareTime.substring(0,2) == "07" || rideshareTime.substring(0,2) == "07" || rideshareTime.substring(0,2) == "08" || rideshareTime.substring(0,2) == "09" || rideshareTime.substring(0,2) == "10" || rideshareTime == "11:00:00")

答案 1 :(得分:2)

由于您需要从06:00:00到11:00:00的值,您可以使用正则表达式来测试字符串或将其解析为数字并使用<或>。

对于第一种方法,字符串格式为0 [6-9]:[0-6] [0-9]:[0-6] [0-9]或10:[0-6] [ 0-9]:[0-6] [0-9]或11:00:00(假设小时:分钟:秒)。

注意:上面的表示是不是正则表达式,我写的是为了传达这个想法。您可以将它们转换为有效的正则表达式。

或者

将字符串解析为三个数字 - 小时,分钟和秒,然后进行测试,即

total_seconds = hours*3600 + minutes*60 + seconds 
if(total_seconds >= 6*3600 && total_seconds <= 11*3600)
    ...do my job....

此外,您可以查看第三方库以处理更多时间格式,这将减少工作量。

答案 2 :(得分:2)

如果您的rideshareTime是一个字符串,则可以使用正则表达式/[0-9]+:[0-9]+:[0-9]+/g

if (time.match(/[0-9]+am:[0-9]+pm/g).length) {
    if (rideshareTime.match(/[0-9]+:[0-9]+:[0-9]+/g).length && _isRideShareTimeValid(rideshareTime)) {
        if (luggageSpace == "Yes") {
            if (rideshareSeats >= seatsAvailable && luggageSpace == rideshareLuggage && womenOnly == rideshareWomen) {
                $obj.closest('.rideshare-item').show();
            }
        } else {
            if (rideshareSeats >= seatsAvailable && womenOnly == rideshareWomen) {
                $obj.closest('.rideshare-item').show();
            }
        }
    }
}


_isRideShareTimeValid(time){
  time = time.replace(':','');
  timeNumbers = time.split('').map(function(a){ return parseInt(a);});
  return time.length >= 3 && time.length <= 6 && timeNumbers.every(function(p){ p!=NaN});
}