Error encountered: Invalid date within foreach loop

I'm perplexed as to why one date is considered valid while the others are labeled as "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">1st May, 2022</span>
<span class="roadmap__time">16th June, 2022</span>
<span class="roadmap__time">3rd March, 2022</span>
<span class="roadmap__time">3rd July, 2022</span>
<span class="roadmap__time">9th July, 2021</span>

Answer №1

The key to the effectiveness of using 1 mar(ca) as a date format is that the Date.parse function only considers the first 3 characters and automatically assumes it is March

Check out this code snippet that handles conversion in both directions

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving an image from an input file and setting it as the background of a div element

I am currently developing a whack the mole game using Vanilla JS, and I'm attempting to allow players to choose their own target by uploading an image file. However, despite days of searching for a solution, I have not been successful. HTML: <inpu ...

Replicate and modify the settings on a fresh radio inspection

In my approach, I am avoiding direct HTML editing and instead utilizing JavaScript/jQuery to accomplish the desired outcome. Initially, one input (specifically 'Express Shipping') is pre-selected by default. The goal is to clone/copy the HTML co ...

IE11 encounters an error labeled SCRIPT1010, signaling an expected Identifier when compiled

Lately, I've been encountering a strange issue in Vue.js. Here's the thing: my application runs smoothly on all browsers locally (yes, even IE 11). But when I compile it using npm run build and deploy it to my server (which essentially serves con ...

What's the best way to integrate Bootstrap into my HTML document?

Hey there, I'm new to the coding world and just started learning. I could use some assistance with including Bootstrap v5.1 in my HTML code. The online course I'm taking is using an older version of Bootstrap, so I'm having trouble finding t ...

Ensure that everything within the Container is not see-through

Fiddle:https://jsfiddle.net/jzhang172/b09pbs4v/ I am attempting to create a unique scrolling effect where any content within the bordered container becomes fully opaque (opacity: 1) as the user scrolls. It would be great if there could also be a smooth tr ...

Tips for muting console.log output from a third-party iframe

As I work on developing a web application using NEXT.js, I am encountering an issue with a third party iframe that is generating numerous console logs. I am seeking a way to silence these outputs for the iframe. The code in question simply includes an < ...

Exporting State From Another ReactJS Module: A Step-by-Step Guide

A new project is underway with 3 students who are diving into the world of React for the first time. To make our work more efficient, I suggested dividing the code so that each student could work on a different aspect simultaneously. However, when I attemp ...

Transforming a function into an array in TypeScript

I attempted to use the map() function on a dataURL array obtained from the usePersonList() hook, but I am struggling to convert my function to an array in order to avoid errors when clicking a button. import Axios from "axios"; import React, { us ...

Verify if an element with a specific index exists within an array

$.each(constructions, function(i,v) { if ($.inArray(v.name, map[ii].buildings) == -1) {//do something} }; In this scenario, the constructions array consists of unique objects with a name attribute. On the other hand, map[ii].buildings is an array contain ...

Using Javascript to apply styling only to the first class element in the document

I am facing a challenge with styling programmatically generated classes and inputs. Here is an example of the structure: <div class="inputHolder"> <input type="button" class="inputclss" value="1"> </ ...

Plugin for managing responses other than 200, 301, or 302 in forms

Currently, I am using the jQuery Form Plugin in my project. Everything works smoothly when the server sends a 200 response as it triggers the success listener seamlessly. However, according to the standard protocol, the browser automatically handles 301 ...

Calling a Coldfusion function from JavaScript/jQuery using a remote server connection

Although I am well-versed in JavaScript/jQuery, I am a newcomer to ColdFusion. After extensive research, I still can't figure out what seems like it should be a simple problem. My goal is to trigger a server-side call to a ColdFusion function from wi ...

Disabling the ability to edit the rightmost portion of an input number field

I am looking for something similar to this: https://i.stack.imgur.com/ZMoNf.jpg In this case, the % sign will be shown in the input field by default and cannot be changed or removed. The user is only able to modify the number to the left of the % sign. P ...

Ensure that both the top row and leftmost column are fixed in a vertical header using JQuery DataTable

Check out the implementation of vertical header flow in Datatables by visiting: https://jsfiddle.net/2unr54zc/ While I have successfully fixed the columns on horizontal scroll, I'm facing difficulty in fixing the first two rows when vertically scroll ...

The distinction between a keypress event and a click event

Due to my eyesight challenges, I am focusing on keyboard events for this question. When I set up a click event handler for a button like this: $("#button").on("click", function() { alert("clicked"); }); Since using the mouse is not an option for me, ...

The jQuery AJAX request is not returning a truthy value when parsing

On my website, I am dealing with a large form and using the serialize() method to process it. However, I have encountered an issue: After completing the form, the result always returns false. I checked this using Firebug. Even though data.ok == true has ...

Preserving state during navigation and router refresh in Next.js version 13

In the component below, we have a Server Component that fetches and renders data. When router.refresh() is called on click, it reruns the page and refetches the data. However, there is an issue with Nextjs preserving the state. Even though the server compo ...

Webpack creating a bundle file with no content

I'm currently facing a challenge with webpack/webpack-stream while trying to bundle some JavaScript files. The issue I am encountering is that, despite generating the bundle.js file, it turns out to be empty. To ensure clarity, I've provided the ...

Eliminate the page base from WordPress URLs to enhance code customization

I came across an interesting thread that caught my attention: Removing category & tag base from WordPress URL - no plugin needed After trying out various solutions mentioned in the thread, such as modifying the functions.php file and using the wp-no-categ ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...