Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/3085937/safari-js-cannot-parse-yyyy-mm-dd-date-format

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...