Reputation: 4542
I am trying to validate if the given time value is less than or equal to 13.
I get the values from UI like hour and minutes and am/pm
.
How do I check if total hours does not exceed 13 in JavaScript?
After some calculation I have hour and minutes and I tried to validate as follows:
if ((fromHour != 13 & fromMinute == 0) & (toHour < fromHour & toMinute == 0)) //
{
alert("Time cannot be greater than 13 hours");
}
but it is not working as I expected. What do I need to change?
Upvotes: 1
Views: 1221
Reputation: 782683
Convert the times to minutes by multiplying the hour by 60 and adding the minutes. Then subtract the times and see if it's less than 13*60
. And if the times cross over midnight, so that the to
time is lower than the from
time, add the number of minutes in a day first.
fromTime = fromHour * 60 + fromMinute;
toTime = toHour * 60 * toMinute;
if (toTime < fromTime) {
toTime += 60*24;
}
if (toTime - fromTime > 13*60) {
alert("Time cannot be greater than 13 hours");
}
Upvotes: 1