Converting an array into a JavaScript Date object

I am currently working with an array of dates and looping through each element. The elements within the array are not date objects but rather strings, I believe.

When I print each of the elements to the console, they appear as follows:

2015,09,19 2015,09,21

I am attempting to convert these strings into proper date formats, however, I keep encountering errors stating that the dates are invalid. For example, when I try the following:

var temp = new Date(2015,09,21);

everything works perfectly. But when I attempt to do it dynamically like this:

var temp = new Date(datax[i]);

I receive a message saying "invalid date."

Below is the full loop for reference:

for (var i = 0; i < datax.length; i++) {
    var temp = new Date(datax[i]); // fails says invalid date
    // var temp = new Date(2015,09,21); //works fine but is statically assigned (want to get it from array)
    console.log(temp);
}

Any assistance would be greatly appreciated. Thank you!

Answer №1

When the content of an array is in the form of a string like "2015,19,09", you can parse it by replacing commas with hyphens using:

new Date(datax[i].replace(/,/g, "-"));

This should work fine.

The string "2015,19,09" may not be valid for the date object to parse, but "2015-19-09" will be acceptable.

If you prefer the same pattern as your manual attempt, first split the string and convert it into an array like so:

var temp = datax[i].split(",");
temp = new Date(temp[0], temp[1], temp[2]);

If the content of the array itself is an array, you can directly create a date object by passing the elements of the inner array:

new Date(datax[i][0], datax[i][1], datax[i][2]);

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

What is the reason for requiring both a promise and a callback in order to store JSON data in a global variable?

In order to expose fetched JSON data to a global variable, it is necessary to use either a promise or a callback function. However, my current code is utilizing both methods... Currently, I am creating a promise using the .done function in jQuery. Within ...

When hovering over a div, reveal another div on top of a third div

Imagine two adjacent divs, A on the left and B on the right with some other elements in between. Is it possible to have a third div, C, appear over div A when hovering over div B? I can control the display property using CSS, but I am unsure how to make d ...

Adjust the color of TextareaAutosize component using mui in React

Just starting out with React and getting acquainted with mui components. Experimenting with setting the color of a TextareaAutosize mui component using this code: import * as React from 'react'; import TextareaAutosize from '@mui/material/T ...

Adjusting mesh rotation on elliptical curve using mousewheel scrolling

I have arranged several plane meshes in a uniform manner along an elliptical curve. During the animation loop, I am moving them along the ellipse curve using curve.getPointAt with time delta and applying the matrix. Additionally, I am attempting to incor ...

The console is throwing an error: ReferenceError: The variable $ has not been defined

I am having issues when trying to dynamically add a div upon selecting a checkbox in a Django template. The error message Uncaught ReferenceError: $ is not defined keeps appearing in the console. Here is the template code: {% extends 'base_layout.htm ...

`Cannot recompile the `Product` model as it has already been compiled. Please try again

I attempted to reference my productSchema within my purchaseSchema but encountered the following error: OverwriteModelError: Cannot overwrite Product model once compiled. What steps can I take to resolve this issue? Here is my product schema: mongoose = ...

What strategies can I use to keep an element in place while implementing parallax scrolling?

Looking for some assistance with my Codepen project. I am attempting to replicate a layout similar to this BBC article design from the past, but hitting a roadblock with getting my image to be position fixed based on scrolling. I believe that if I can suc ...

What kind of data does this collection hold, and what is the best method to retrieve its stored values?

I recently received a code to program a logic for and I have successfully figured out my algorithm. However, I am facing difficulty determining the datatype of a particular declaration. My task involves comparing the values of "skills" in each row to &apos ...

Retrieve the response retrieved from AJAX/jQuery and insert it into the designated form input field

When a user inputs an address into this form and clicks on the verify address button, the following script is executed: $('#verify').click(function () { var address = $('input[name=address]'); var city = $('input[name= ...

Guide to dynamically assigning v-on with v-for

I'm working on a Vue code that dynamically creates a menu using v-for, with each element requiring a different method when clicked. Here's what I have so far: <span v-for="(menuItem, index) in menuItems" :key="index"> ...

Troubleshooting the Issue of Angular Model Not Refreshing in Angular.js

Running into an issue with my directive where the model isn't updating as expected. Here's a snippet of my HTML code: <div class="text-area-container"> <textarea ng-model="chatText" ng-keyup="updateCount(chatText)">< ...

Ways to resolve the issue of the 'setConfirmDelete' property not being found on type 'JSX.IntrinsicElements' in React.js

index.tsx const setConfirmDelete = (state, close) => { return ( <Modal show={state} onHide={close}> <Modal.Header> <Modal.Title>Title</Modal.Title> </Modal.Header> <Modal.Body> 'T ...

Inject HTML entities, escaped for CSS, dynamically using JavaScript

My goal is to dynamically generate a list of HTMLElements with unique data-* attributes that correspond to various HTML Entities. These attributes will then be utilized by CSS to display content in pseudo elements like this: li:after { content: attr(dat ...

Display a unique button and apply a strike-through effect specifically for that individual list item

I've encountered an issue with my code that is causing problems specifically with nested LI elements under the targeted li element: $('#comment-section .comment-box a#un-do').hide(); $('#comment-section ul li[data-is-archived="true"]& ...

Discovering Ways to Navigate and Search Within XML and JSON Data

Currently, I am receiving a balance sheet report in the form of a JSON or XML object. The JSON format resembles the Row object containing several nested arrays. Among these are different RowTypes such as Header, Section, and Summary Row. My goal is to iden ...

Add a new module to your project without having to rely on the initial

I'm looking to experiment with a module by making some adjustments for testing purposes. You can find the code here. Currently, all I need to do is type "npm install angular2-grid" in my terminal to add it to my project. Here's my concern: If ...

The functionality of Jquery datatables seems to be faulty when navigating to the second page

While utilizing the jQuery datatables plugin, I encountered an issue where the event click function only worked on the first page and not on subsequent pages. To address this problem, I discovered a helpful resource at https://datatables.net/faqs/ Q. My ...

I'm struggling to activate the eventListener on several elements with the same className or ID. Unfortunately, only the initial child is being triggered in my current code implementation

Hello fellow developers, I'm facing an issue while working on a project. I have about ten menu items with the same ID, and I want to be able to edit each one when it is clicked. Here's what I tried using JavaScript: const menuElement = d ...

The click() function in jQuery executing only once inside a "for" loop

This is an example of my HTML code: <!DOCTYPE html> <head> <title>Chemist</title> <link href="stylesheet.css" rel="stylesheet"> </head> <body> <h2 id="money"></h2> <table border="1px ...

The issue of Select2 with AJAX getting hidden behind a modal is causing

I'm currently facing an issue with Select2 within a modal. The problem can be seen here: https://gyazo.com/a1f4eb91c7d6d8a3730bfb3ca610cde6 The search results are displaying behind the modal. How can I resolve this issue? I have gone through similar ...