Skip to content Skip to sidebar Skip to footer

Convert A String To Date

I used to convert a french date 23 décembre 2015 15:03 to Date. It worked for a while. and now it doesn't work, any idea ???? var date = new Date('23 décembre 2015 15:03'); conso

Solution 1:

The only date/time format that the specification requires the Date constructor (or Date.parse, or anything else) to support is a subset/simplification of ISO-8601. Your string is not in that format.

To parse it, you need to either do it in your own code, or use a library like MomentJS (with, in your case, the French locale plugin).

Doing it in your own code isn't hard if that format is reliable:

var months = [
  "janvier",
  "février",
  "mars",
  "avril",
  "mai",
  "juin",
  "août",
  "septembre",
  "octobre",
  "novembre",
  "décembre"
];

function parseThatDate(str) {
  var parts = /(\d{1,2}) ([^ ]+) (\d{4}) (\d{2}):(\d{2})/.exec(str);
  if (!parts) {
    return new Date(NaN);
  }
  var month = months.indexOf(parts[2].toLowerCase());
  if (month == -1) {
    return new Date(NaN);
  }
  return new Date(+parts[3], // Year
    month, // Month
    +parts[1], // Day
    +parts[4], // Hour
    +parts[5] // Minute
  );
}

var str = "23 décembre 2015 15:03";
document.body.innerHTML = parseThatDate(str).toString();

Post a Comment for "Convert A String To Date"