I am using browser date function. I have input like 13/77/7777 which is a invalid date. I do like
new Date('13/77/7777').getTime();
This returns NAN in FF and chrome but in IE it gives a number back. How do i fix this issue.
I am using browser date function. I have input like 13/77/7777 which is a invalid date. I do like
new Date('13/77/7777').getTime();
This returns NAN in FF and chrome but in IE it gives a number back. How do i fix this issue.
The value I get with .getTime()
in IE11 is 183289406400000
.
The date itself comes back as March 18, 7778
.
This is because, quite maddeningly, IE11 is parsing 13/77/7777
in mm/dd/yyyy
format and coming up with the result of "Month 13 and Day 77 of the Year 7777" which (frustratingly and yet unsurprisingly) works out to March 18, 7778
(if you add 13 months and 77 days to January 1, 7777
).
Given that a quick google search turned up no results for any polyfills for the Date
constructor in IE11, I suspect the most reasonable fix would be to sanity-check the string before trying to parse the date with the constructor.
With the caveat that while it's probably not as efficient (or as accurate) as it could be, it should serve as a reasonable example to help you get started. Something like this should do:
function isValidDateString(s) {
"use strict";
if (typeof s !== "string") {
return false; // not a string, exit.
}
var parts = s.split("/");
if (parts.length !== 3) {
return false; // unexpected number of slashes. exit.
}
var d31 = [1, 3, 5, 7, 8, 10, 12];
var d30 = [4, 6, 9, 11];
var mm = parseInt(parts[0]);
var dd = parseInt(parts[1]);
var yyyy = parseInt(parts[2]);
// empirical testing in Chrome & IE11 to get this value. YMMV.
var maxYear = 275760;
var isValidYear = !isNaN(yyyy) && yyyy <= maxYear;
var isDivisbleBy4 = (yyyy % 4 === 0);
var isDivisbleBy100 = (yyyy % 100 === 0);
var isDivisbleBy400 = (yyyy % 400 === 0);
var isLeapYear = (isDivisbleBy4 && !isDivisbleBy100) || isDivisbleBy400;
var isValidMonth = !isNaN(mm) && (mm >= 1 && mm <= 12);
if (!isValidMonth) {
return false;
}
var maxDaysInMonth = 28;
if (d31.indexOf(mm) > -1) {
maxDaysInMonth = 31;
} else if (d30.indexOf(mm) > -1) {
maxDaysInMonth = 30;
} else if (isLeapYear) {
maxDaysInMonth = 29;
}
var isValidDay = !isNaN(dd) && (dd > 0 && dd <= maxDaysInMonth);
if (!isValidDay) {
return false;
}
return isValidMonth && isValidDay && isValidYear;
}
var testsThatShouldFail = [
'13/77/7777', // lousy Smarch weather!
'2/29/2018',
'9/12/275761',
'4/31/2016',
'6/35/2019',
];
var testsThatShouldPass = [
'1/1/1900',
'2/29/2000',
'2/29/2016',
'9/12/275760',
'8/16/2018',
];
console.log('should fail', testsThatShouldFail.map(isValidDateString));
console.log('should pass', testsThatShouldPass.map(isValidDateString));