JS: new Date() is not accepting date string in my own locale (d/m/y)

前端 未结 3 1645
情深已故
情深已故 2020-12-11 01:34

My browser (ie. my OS) should know I\'m in Australia and what the correct date format is. In this case, d/m/y, not m/d/y. However if I run the following code:



        
相关标签:
3条回答
  • 2020-12-11 02:08

    It's pretty simple to convert your date string to a format that will give the expected result ('yyyy/mm/dd' or 'yyyy-mm-dd'):

    new Date("21/11/1968".split('/').reverse().join('/'));
    

    [edit] You may like this more generic method (part of the npm PureHelpers library):

    document.querySelector("#result").textContent = `
      tryParseDate("2017/03/22", "ymd"); // ${tryParseDate("2017/03/22", "ymd")}
      tryParseDate("03/22/2017", "mdy"); // ${tryParseDate("03/22/2017", "mdy")}
      tryParseDate("22-03-2017", "dmy"); // ${tryParseDate("22-03-2017", "dmy")}
    `;
    
    function tryParseDate(dateStringCandidateValue, format = "dmy") {
    
      if (!dateStringCandidateValue) {
          return null;
      }
      
      const mapFormat = format.split("").reduce(function(a, b, i) {
          a[b] = i;
          return a;
      }, {});
      const dateStr2Array = dateStringCandidateValue.split(/[ :\-\/]/g);
      const datePart = dateStr2Array.slice(0, 3);
      const datePartFormatted = [
        +datePart[mapFormat.y], 
        +datePart[mapFormat.m] - 1, 
        +datePart[mapFormat.d]
      ];
      
      if (dateStr2Array.length > 3) {
        dateStr2Array.slice(3).forEach(t => datePartFormatted.push(+t));
      }
      
      const dateTrial = new Date(Date.UTC.apply(null, datePartFormatted));
      return dateTrial && dateTrial.getFullYear() === datePartFormatted[0] &&
              dateTrial.getMonth() === datePartFormatted[1] &&
              dateTrial.getDate() === datePartFormatted[2] 
          ? dateTrial 
          : null;
    }
    <pre id="result"></pre>

    0 讨论(0)
  • 2020-12-11 02:21

    The Date object is very weak. You cannot tell it what format to expect. You can create it with a string in m/d/y like you stated, or new Date(year, month, day[, hours, seconds, milliseconds]);

    0 讨论(0)
  • 2020-12-11 02:30

    new Date(string_date) supports the following Date formats:

    1. MM-dd-yyyy
    2. yyyy/MM/dd
    3. MM/dd/yyyy
    4. MMMM dd, yyyy
    5. MMM dd, yyyy
    0 讨论(0)
提交回复
热议问题