Reputation: 1692
Check the Selected time should is exist in between the time slot.
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");
}
Upvotes: 1
Views: 3839
Reputation: 10612
Using this : Convert HH:MM:SS string to seconds only in javascript
I have created this : https://jsfiddle.net/ceyh4ens/
Only works with 24 hour clocks for the time being, but some simple logic will get around this. The main parts are :
var selectedTimeSeconds = selectedTime.substring(0,5) + ':00'; //splits the string into hours minutes and seconds
If you want to work with 12 hour clocks, you could do more parsing here.
And now your if statements should work :)
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;
}
EDIT
To work with 24 hours you need to check whether its AM or PM. If it's PM, add 12 hours, if it's AM do nothing. Here's the function that does that check :
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
}
Then just pass your string like so :
var selectedTimeSeconds = changeTime(selectedTime);
Working updated fiddle : https://jsfiddle.net/jszuLo9o/
Upvotes: 4