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

Angular API snapshot error: The type 'IJobs' does not match the expected type 'IJobs[]'

Currently, I am in the process of learning and attempting to construct a job board using Angular 10. Although my API setup seems to be functioning properly, when navigating to the job detail page on Chrome, an error is displayed: ERROR in src/app/job-det ...

Retrieve the past week's data based on names using JavaScript

Is there a way to dynamically fetch the past seven day names, starting from today, in JavaScript? I am looking to format the result as follows: (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday). ...

Automatically select a value in MUI AutoComplete and retrieve the corresponding object

I recently set up a list using the MUI (v4) Select component. I've received a feature request to make this list searchable due to its extensive length. Unfortunately, it appears that the only option within MUI library for this functionality is the Au ...

The dictionary of parameters includes an empty value for the parameter 'imageWidth', which is of a non-nullable type 'System.Int32'

I am facing an issue with a function that executes an ajax call to an ActionResult. It sends a base64 string of an uploaded image along with some additional parameters containing information about the dimensions of the image. The data is sent to the server ...

When evaluating objects or arrays of objects to determine modifications

How can we detect changes in table data when users add input to cells? For example, if a user clicks on a cell and adds an input, the function should return TRUE to indicate that there are changes. If the user just clicks on the cell without making any ch ...

Issue: Execution terminated with error code 1: ts-node --compiler-params {"module":"CommonJS"} prisma/seed.ts

Whenever I run npx prisma db seed, I encounter the following error: Error message: 'MODULE_NOT_FOUND', requireStack: [ '/run/media/.../myapp/prisma/imaginaryUncacheableRequireResolveScript' ] } An error occurred during the execution ...

What are the steps for integrating a CMS with my unique website design?

Currently, I am in the process of creating a unique website for a client using my own combination of html, css, and JavaScript. There is also a possibility that I may incorporate vueJS into the design. The client has expressed a desire to have the ability ...

Parsley JS - Personalized Validation for Ensuring selected Items meet Minimum Value Requirements

Is it possible to validate a form so that at least 5 select boxes are set to Yes? If there are fewer than 5, the form should not submit and display an error message. I believe a custom validator is needed for this task. To see a complete example, check ou ...

What is the best way to shorten text in Angular?

I am looking to display smaller text on my website. I have considered creating a custom pipe to truncate strings, but in my situation it's not applicable. Here's what I'm dealing with: <p [innerHTML]="aboutUs"></p> Due to t ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

Receiving a 401 error while attempting to make an axios get request with authentication headers

I have been utilizing axios in my React project to fetch data from MongoDB. However, I am facing a challenge with the axios get requests returning a 401 error when I include my auth middleware as a parameter. This middleware mandates that the user must pos ...

The process of extracting data from a form and storing it as global variables

Consider the following example: This is our HTML form <form action="test1" method="GET" name="frm"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> <i ...

Optimal Placement for FB.Event.subscribe

Here is the code I have implemented on my website for the Facebook Like and Share buttons. The functionality works seamlessly. When I click the Like button, a notification is promptly displayed on my Facebook profile page. Additionally, Facebook automatic ...

Activate scroll event when image src changes in Angular using jQuery

Seeking assistance with utilizing jQuery to scroll to a specific thumbnail inside a modal when left/right arrows are pressed. The modal should appear when the user clicks on an image. I've managed to implement scrolling upon clicking a thumbnail, but ...

Display or conceal elements using the unique identifier selected from a dropdown menu in JavaScript

I have been searching the internet for a solution to my issue but nothing seems to be working. Here is the problem: Unfortunately, I cannot modify the TR TD structure and am unable to use DIVs. I am trying to dynamically display certain TD elements based ...

What is causing this code to not produce the expected result of 8.675?

Recently, I encountered a challenge on freecodecamp I managed to write the code successfully, but unfortunately, my browser crashed and I lost all the progress. When I attempted to rewrite the code, it was returning an incorrect answer (a value of 2). I& ...

Oops! The type error is indicating that you tried to pass 'undefined' where a stream was required. Make sure to provide an Observable, Promise, Array, or Iterable when working with Angular Services

I've developed various services to interact with different APIs. The post services seem to be functioning, but an error keeps popping up: ERROR TypeError: You provided 'undefined' where a stream was expected. Options include Observable, ...

Tips for utilizing Async/Await within an expressjs router

Having trouble with Async/Await in my Nodejs project. I'm a beginner with Nodejs and facing an issue connecting to my mongodb collection through my repository. When I integrate my controller with the repository, I end up getting a null response. Take ...

What is the best way to display a jQuery UI dialog when the page is reloaded?

I am trying to display a jQuery UI dialog when the user tries to reload or close the browser. Here is my code snippet: $(window).bind('beforeunload', function () { $("#confirm").dialog({ width: 500, modal: true, buttons: { ...

When attempting to convert large objects into JSON using JSON.stringify, a RangeError is thrown due to

Trying to convert a massive JavaScript Object into a string using JSON.stringify in my Node.js application. The objects are extremely large (tens of mega bytes) and do not contain any functions. I need to save the serialized objects to a file. However, I a ...