开发者

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

My browser (ie. my OS) should know I'm in Australia and what the correct date format is. In 开发者_如何学Cthis case, d/m/y, not m/d/y. However if I run the following code:

alert(new Date("21/11/1968"))

The result is "Thu Sep 11 1969". It is thinking the month comes first and adjusting accordingly.

Why is this? Is the answer to always use a universal format as input to date functions, or is there a way to tell the browser to expect dates input in my locale format?


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>


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


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


You need to parse it using a new date object like

const myDate = new Date('Wed Dec 30 2020 00:00:00 GMT-0500 (Eastern Standard Time)')

Then convert it:

const dateFormatted = myDate.toLocaleDateString("en-US")

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜