Struggling to accurately convert the string into a date object

I have an array of objects structured like this:

const days = [
{
    _id: 12312323,
    date : '30/12/2021',
    dateStatus : 'presence'
},
...
]

I am looking to convert the date property from a string to a Date object using the following method:

const convertToDateObject = (dateString: string): Date => {
    const dateParts: any[] = dateString.split("/");
    return new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
};

for (let i = 0; i < days.length; i++) {
    const d = days[i].date as string;
    days[i].date = convertToDateObject(d);
}

However, the conversion results in a format similar to

'Wed Dec 01 2021 00:00:00 GMT+0100 (Central European Standard Time)'
, rather than the desired format at 2021-11-30T23:00:00.000Z.

I am confused because when the object does not contain the _id property, the formatting works correctly and provides the expected output, but if it includes the _id property, it gives me a different format. Why is this happening?

Answer №1

However, the output of this process transforms the date value into a particular format...

That's not entirely accurate. It actually provides you with a Date object, which doesn't inherently have a specific "format." You can extract the date/time details from the object either in your local time zone (apparently GMT+0100 in your case) or in UTC by using different methods. To access information in local time, you would utilize functions like getHours, getMinutes, getSeconds, toString, toLocaleString, and so on. Meanwhile, to retrieve data in UTC, you would employ functions such as getUTCHours, getUTCMinutes, getUTCSeconds, toUTCString, among others.

The particular constructor you are employing does function based on local time. Essentially, it creates a Date object for midnight (as no hours, minutes, seconds, or milliseconds are specified) in your local time zone (due to the usage of new Date). If you wish to obtain midnight in UTC, you could achieve this by using

new Date(Date.UTC(+dateParts[2], dateParts[1] - 1, +dateParts[0]));
instead. The main distinction lies in the exact point in time represented by the resulting Date object (midnight on the given date in local time versus midnight on the same date in UTC).

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

Including input within a component causes the input to capture all click events

I've been working on a project where I need to create a color picker component. When you click on the .swatch element, a popover opens up with a .cover div that covers the whole screen. Clicking on the cover closes the popover, following standard beha ...

Tips for breaking apart elements of a JavaScript array when a specific delimiter is present in an object property

I am facing a challenge with an array of objects where some properties contain commas. My goal is to split these properties into new objects and recursively copy the rest of the properties into new array elements. For example, consider this original array ...

Initiate node and PM2 application using a batch file

Currently, I have a chat-bot application running on Node.js, which I always keep active using pm2. I am looking to streamline the process of launching the application. Instead of having to run the start command from the console every time, I would like to ...

Having trouble making "jQuery.inArray" function properly in my code

Recently, I made a small interaction where list items are displayed and rotated when clicked - check it out here: http://jsfiddle.net/S79qp/430/ Lately, due to compatibility issues with IE8, I had to switch from using .indexOf() to jQuery.inArray. However ...

What is the proper method for delivering Javascript code with rendered HTTP to a client?

During the development process, I made a decision to switch to server-side rendering in order to have better control and take advantage of other benefits. My web application relies heavily on AJAX with no url redirecting, creating a website that dynamicall ...

I am unable to retrieve the local variable beyond the function

I'm having trouble accessing a local variable outside of a function even though I have initialized it before the function is called. <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jq ...

Material UI Alert component not appearing on screen?

Greetings, I have been working on polishing my app now that it is finally complete. I decided to enhance the aesthetics by replacing all instances of window.alerts with Alerts from MUI (since they look way better). However, for some reason, they are not sh ...

Calculating the percentage in a jQuery Slider

For a while now, I've been using var slideWidth = 420; to set the width of sliders and then $('#slideInner').css('width', slideWidth * numberOfSlides); to calculate the total width of all sliders effectively in pixels. An Issue Ar ...

Exploring the possibilities of utilizing React server components in my project

I am interested in experimenting with the new React API for making server-side component calls. However, I am unable to find any information on how to begin a project using server components. In an example of source code that I stumbled upon, it mentioned ...

angular: setting default selected items in dynamically generated options

After looking at the example provided here, I noticed that all three select options have the same value. How can I ensure that each option has a different selected value? This is what I currently have: <li ng-repeat="tarea in tareas"> <inp ...

Can you provide guidance on how to specifically specify the type for the generics in this TypeScript function?

I've been diving into TypeScript and experimenting with mapped types to create a function that restricts users from extracting values off an object unless the keys exist. Take a look at the code below: const obj = { a: 1, b: 2, c: 3 } fun ...

How can I change an array to a string in JavaScript/jQuery and add a specific

Currently, I am tasked with the challenge of converting an array into objects. Furthermore, I also need to add something before each object is displayed. var arrayList = ["image1.jpg","image2.jpg","image3.jpg"]; The desired outcome should look like this ...

Potentially null object is present in a callback

The code I have is as follows: let ctx = ref.current.getContext("2d"); if(ctx){ ctx.lineWidth=1; // this line executes without errors ctx.strokeStyle=props.barStroke??"darkgray";// this line execut ...

Pressing the "Enter" key in a .Net WinForm Browser Control

How can I simulate the Enter key press event on a web page using the GeckoFX Web Control? I am unable to use SendKeys.Send({ENTER}) Is there a method to trigger the Enter key using JavaScript within a webpage? ...

The Vue3 module does not have any exported members available

I am seeking assistance with a Vue component. I have encountered an error message that states: Failed to compile. src/components/Btn/Btn.vue:11:14 TS2305: Module '"../../typings/button-type"' has no exported member 'ButtonType&apo ...

Exploring the integration of React Context API within a Next.js application to streamline the authentication process

I am looking to build a react app using Next.js. However, I am currently stuck and need assistance in figuring out how to proceed. I have implemented user authentication on the backend with node.js, passport.js, passport-local-mongoose, and express.sessi ...

Intentionally introduce discrepancies in the errors during validation of an object using hapi/joi

const validationSchema = Joi.object().keys({ Id: Joi.number().required(), CustomerName: Joi.string() .trim() .required() .when('$isInValidCustomer', { i ...

Cypress eliminating the "X-CSRFToken" header

There seems to be an issue with the Cypress test runner where it is removing X-CSRFToken from the request header, leading to a 403 Forbidden error. I have compared the headers between a manual run and a Cypress test run, and you can see the difference in t ...

The type 'Observable<Response>' does not include a property called 'map'

I recently started learning angular and npm, but encountered an error while trying to replicate some code from a source I found (linked here). It seems like the error is related to my development environment, but I'm having trouble pinpointing the ex ...

Adding a new row to a table is causing issues with jQuery

var info = [{ "pin": "015-08-0011-000-01", "arp": "015-08-0011-000-01", "tin": "342-432-423-000", "firstname": "John", "middlename": "James", "lastname": "Jones", "suffix": "", "qtr": "1st ...