星期二, 3月 05, 2013

[Javascript] Date.parse在safari NaN解決方法


最近在Safari使用Date.parse的NaN問題,不過以下這個解法,少算了時分秒。
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 theDate.prototype.toISOString is available, e.g.:
if (typeof Date.prototype.toISOString == "function") {
  // ES5 ISO date parsing available
}

沒有留言:

張貼留言

留個話吧:)