检查时间段之间的时间

时间:2016-11-03 10:00:27

标签: javascript date compare date-conversion date-comparison

检查时间段之间是否存在所选时间。

var selectedTime = 01:30 AM
var startTime = 12:00 AM
var endTime   = 01:00 PM
/* need logic below in below code without date in Date Object*/
 var startTime = Date.parse('01/01/2001 '+startTime);
 var endTime = Date.parse('01/01/2001 '+endTime);

if(selectedTime <= startTime && selectedTime >= endTime)
{
  alert("Time in beween interval");
}else{
  alert("Time is not with in the time Slot");
}

1 个答案:

答案 0 :(得分:3)

使用此:Convert HH:MM:SS string to seconds only in javascript

我创建了这个:https://jsfiddle.net/ceyh4ens/

目前仅适用于24小时制,但一些简单的逻辑可以解决这个问题。主要部分是:

var selectedTimeSeconds = selectedTime.substring(0,5) + ':00'; //splits the string into hours minutes and seconds

如果您想使用12小时制,那么您可以在此处进行更多解析。

现在你的if语句应该有效:)

&#13;
&#13;
var selectedTime = '11:30 PM'
var startTime = '12:00 AM'
var endTime = '13:00 AM'

var selectedTimeSeconds = selectedTime.substring(0,5) + ':00';
var startTimeSeconds =  startTime.substring(0,5) + ':00';
var endTimeSeconds = endTime.substring(0,5) + ':00';

var selectedTimeSecondsParsed = hmsToSecondsOnly(selectedTimeSeconds) //pass to convert to seconds function
var startTimeSecondsParsed = hmsToSecondsOnly(startTimeSeconds)
var endTimeSecondssParsed = hmsToSecondsOnly(endTimeSeconds)

console.log(selectedTimeSecondsParsed)
console.log(startTimeSecondsParsed)
console.log(endTimeSecondssParsed)

  /* need logic to convert time to Date Format */

  if (selectedTimeSecondsParsed >= startTimeSecondsParsed && selectedTimeSecondsParsed <= endTimeSecondssParsed) { //if its between
   alert("Time in beween interval");
  } else {
   alert("Time is not with in the time Slot");
  }

function hmsToSecondsOnly(str) {
  var p = str.split(':'),
    s = 0,
    m = 1;

  while (p.length > 0) {
    s += m * parseInt(p.pop(), 10);
    m *= 60;
  }

  return s;
}
&#13;
&#13;
&#13;

修改

要24小时工作,您需要检查其上午或下午。如果它是PM,则添加12小时,如果它没有做任何事情。这是检查的功能:

function changeTime(time) {
  var thisTime;
  var thisHour = +time.substring(0, 2);
  if (time.substring(6, 8) == 'PM') {
    //add 12 hours to make it 24 hour clock
    thisHour += 12;
  }

  return thisHour + time.substring(2, 5);//concatenate with the rest
}

然后就像这样传递你的字符串:

var selectedTimeSeconds = changeTime(selectedTime);

更新小提琴:https://jsfiddle.net/jszuLo9o/