Does anyone know why in Firefox if you execute the code below it will validate it as a date if the string passed in is four numbers and only four numbers? In every other browser I tested with (IE, Chrome) it will always return as not a date.
Being that the spec, as pointed out by Marcel Korpel below, states that it should fall back to use the Firefox’s implementation-specific fall back I am really wondering why Firefox’s fall back displays this anomaly.
function isDate(sDate) {
var temp = new Date(sDate);
if (temp.toString() == "NaN" || temp.toString() == "Invalid Date") {
alert("Not a Date");
} else {
alert("Is a Date!");
}
}
If you pass a string to the
Dateconstructor, the string should be in a format recognized by the parse method (IETF-compliant RFC 1123 timestamps) (source: MDC). Everything else results in implementation specific behaviour and will vary across browsers.I suggest you don’t use strings at all and either use three numbers representing year, month and day (mind that month numbers begin at 0 (= January)), or use one number, the number of milliseconds since 1 January 1970 00:00:00 UTC.
UPDATE: seeing your example,
outputs
so Firefox apparently recognizes
'0123'as a year number.UPDATE 2: I think MDC’s description of
Date.parsecontains the answer to your question:The ISO 8601 page specifies (section ‘Formats’):
So when relying on ISO 8601, a string only containing four numbers will be recognized as a year number.