0

I don't understand why one date is good and the rest show "Invalid Date".

const blocksDate = document.querySelectorAll(".roadmap__time");
blocksDate.forEach((block) => {
  const dateString = block.innerHTML;
  const dateBlock = new Date(dateString);
  const currentDate = new Date();
  console.log(dateBlock);
});
<span class="roadmap__time">1 maja, 2022</span>
<span class="roadmap__time">16 czerwca, 2022</span>
<span class="roadmap__time">3 marca, 2022</span>
<span class="roadmap__time">3 lipca 2022</span>
<span class="roadmap__time">9 lipca 2021</span>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
ka1jv8
  • 13
  • 3
  • seems like it would have something to do with locale but really I'm not familiar with such things. One possibility is that maja is a valid date in a different locale (so it works) and the rest are not recognized (because polish is not the current locale). But I'm not sure that locale is even the right word here. – topsail Jul 02 '22 at 14:22
  • @topsail—parsing of unsupported formats is implementation dependent. It should have nothing to do with locale since many hosts have no idea of their location. – RobG Jul 03 '22 at 12:21
  • The dupe is not answering the question. – mplungjan Jul 03 '22 at 17:19

1 Answers1

0

The reason 1 mar(ca) works is that the Date.parse sees only the first 3 chars and guesses March

Here is a script that converts both ways

const months = ["STY", "LUT", "MAR", "KWIE", "MAJ", "CZE", "LIP", "SIE", "WRZ", "PAZ", "LIS", "GRU"]
const options = {
  year: "numeric",
  month: "long",
  day: "numeric"
};

const blocksDate = document.querySelectorAll(".roadmap__time");
blocksDate.forEach((block) => {
  const dateString = block.textContent.trim();
  const ddmmmyyyy = dateString.split(/[ \/]/);
  let dd, mmm, yyyy;
  if (ddmmmyyyy.length === 3) {
    dd = ddmmmyyyy[0];
    mmm = ddmmmyyyy[1]
    yyyy = ddmmmyyyy[2];
  } else {
    dd = 1;
    mmm = ddmmmyyyy[0];
    yyyy = ddmmmyyyy[1];
  }
  if (!isNaN(mmm)) mmm = months[+mmm-1]
  mmm = mmm.slice(0,3)

  console.log(dd, mmm, yyyy);
  const dateBlock = new Date(yyyy, months.indexOf(mmm.toUpperCase()), dd, 15, 0, 0, 0);
  console.log(dateBlock);
  const plDate = dateBlock.toLocaleDateString("pl", options)
  console.log(plDate)

});
<span class="roadmap__time">1 Maja, 2022</span>
<span class="roadmap__time">16 czerwca, 2022</span>
<span class="roadmap__time">3 marca, 2022</span>
<span class="roadmap__time">3 lipca 2022</span>
<span class="roadmap__time">9 lipca 2021</span>
<time class="roadmap__time"> 15/07/2022</time>
<span class="roadmap__time">marca/2022</span>
<span class="roadmap__time">Lipca/2022</span>
<span class="roadmap__time">05/2022</span>
<span class="roadmap__time">06/2022</span>
<span class="roadmap__time">lipca, 2021</span>
<span class="roadmap__time">lipca 2021</span>
mplungjan
  • 169,008
  • 28
  • 173
  • 236