Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

javascript - 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 this 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...