Convert a string to date

后端 未结 1 748
暗喜
暗喜 2021-01-29 08:28

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 = ne         


        
相关标签:
1条回答
  • 2021-01-29 09:03

    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();

    0 讨论(0)
提交回复
热议问题