My JavaScript code is working on on Chrome, IE, and Firefox, but when it gets to safari it doesn’t work. I believe I have narrowed down the problem: When creating a ‘new Date’ in JavaScript, all other browsers recognize my string except safari.
HTML:
<form>
<input id="timeIn" value="1:00 AM"/>
<input id="dateIn" value="1/20/2012"/>
<input id="timeOut" value="2:00 AM"/>
<input id="dateOut" value="1/21/2012"/>
</form>
JavaScript:
function calcHours() {
// Build datetime objects and subtract
var timeIn = new Date($('#timeIn').val() + $('#dateIn').val());
if(!isValidDate(timeIn)) return -1;
var timeOut = new Date($('#timeOut').val() + $('#dateOut').val());
if(!isValidDate(timeOut)) return -1;
var hours = (timeOut - timeIn)/(1000*60*60);
return hours.toFixed(1);
}
function isValidDate(d) {
console.log(d);
if ( Object.prototype.toString.call(d) === "[object Date]" ) {
// it is a date
if ( isNaN( d.getTime() ) ) { // d.valueOf() could also work
// date is not valid
console.log("isn't valid");
return 0;
}
else {
// date is valid
console.log("is valid");
return 1;
}
}
else {
// not a date
console.log("isn't valid");
return 0;
}
}
var hours = calcHours();
console.log("Hours:", hours);
I have made a js fiddle: http://jsfiddle.net/mq72k/7/. If you open it up in chrome, it will work fine. If you open it up in Safari, it will say invalid date for the same inputs and not work at all. I have also tried varying the string a bit, adding spaces, different order ect.
Does any one have any ideas how to fix this cross browser compatibility issue?
Frankly, I’m surprised other browsers parse the string correctly, as the string you give to the date object is
1:00 AM1/20/2012. Put the date first and add a space in between.http://jsfiddle.net/mq72k/8/