Reputation: 173
I changed my strings to 24hr format, but why are the times not comparing what am i doing wrong?
function getTwentyFourHourTime(amPmString) {
var d = new Date("1/1/2013 " + amPmString);
return d.getHours() + ':' + d.getMinutes();
}
var inputStart = "6:00 AM";
var inputEnd = "10:00 PM";
var startDay = getTwentyFourHourTime(inputStart);
var endDay = getTwentyFourHourTime(inputEnd);
if(startDay < endDay){
alert("works!");
}
Upvotes: 1
Views: 594
Reputation: 2604
This happens because you are comparing Strings. When you do return d.getHours() + ':' + d.getMinutes();
It returns a string and "6:0"
is greatter than "22:0"
.If you return only d
your code will work properly.
function getTwentyFourHourTime(amPmString) {
var d = new Date("1/1/2013 " + amPmString);
return d;
}
var inputStart = "6:00 AM";
var inputEnd = "10:00 PM";
var startDay = getTwentyFourHourTime(inputStart);
var endDay = getTwentyFourHourTime(inputEnd);
if(startDay < endDay){
alert("works!");
}
Check my Demo
Hope it Helps you.
Upvotes: 2