Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 484
ingredient_15939 Avatar asked Aug 23 '11 18:08

ingredient_15939


1 Answers

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>
like image 177
KooiInc Avatar answered Oct 13 '22 00:10

KooiInc