Safari JS cannot parse YYYY-MM-DD date format?

Austin Hyde picture Austin Hyde · Jun 21, 2010 · Viewed 46.6k times · Source

In a project I am working on, I need to validate a date entered into an <input type="date">

With Safari 4/5 (on Mac OSX) the Javascript fails to parse dates of the format YYYY-MM-DD, returning NaN instead of the expected epoch timestamp.

I am using the following technique to validate the field just before the form is submitted:

//value = '2010-06-21'
var stamp = Date.parse(value);
if (isNaN(stamp)) {
    //notify user
} else {
    value = new Date(stamp).format_mysql();
}

Where format_mysql() is a prototype function that formats the date (correctly) into MySQL Date-Time format (YYYY-MM-DD).

Replacing the -'s with /'s (YYYY/MM/DD) yields a "correct" timestamp.

I should note that the field should accept any date format, not just YYYY-MM-DD, and that though I would like to, I cannot use libraries like Date.js

How can I fix this, or is there a better way to parse/validate a date?

Answer

Christian C. Salvad&#243; picture Christian C. Salvadó · Jun 21, 2010

The behavior of the Date.parse method is implementation dependent, on ECMAScript 5, this method can parse ISO8601 formatted dates, but I would recommend you to make the parsing manually.

Some time ago I've made a simple function, that can handle a format specifier argument:

function parseDate(input, format) {
  format = format || 'yyyy-mm-dd'; // default format
  var parts = input.match(/(\d+)/g), 
      i = 0, fmt = {};
  // extract date-part indexes from the format
  format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; });

  return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']]);
}

parseDate('06.21.2010', 'mm.dd.yyyy');
parseDate('21.06.2010', 'dd.mm.yyyy');
parseDate('2010/06/21', 'yyyy/mm/dd');
parseDate('2010-06-21');

Also you could detect the ECMAScript 5 behavior to parse ISO formatted dates, you can check if the Date.prototype.toISOString is available, e.g.:

if (typeof Date.prototype.toISOString == "function") {
  // ES5 ISO date parsing available
}