I have an array of object like this:
const days = [
{
_id: 12312323
date : '30/12/2021'
dateStatus : 'presence'
},
...
]
and I want to convert the date property from string to date object this way:
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);
}
But this returns this converts the date value to this format 'Wed Dec 01 2021 00:00:00 GMT+0100 (Central European Standard Time)' instead of this format 2021-11-30T23:00:00.000Z**.
I am actually lost because when the given object does not have the _id property the formatting is working properly and it returns the wanted format, but when it does have the _id property then it returns me another format. Why?
But this returns this converts the date value to this format...
No, it doesn't. It gives you a Date object, which has no "format." You can get the date/time information from that object either in local time (apparently GMT+0100 where you are), or in UTC, depending on what methods you use. To get information from the object in local time, you use getHours, getMinutes, getSeconds (etc.), toString, toLocaleString, and similar. To get information from the object in UTC, you use getUTCHours, getUTCMinutes, getUTCSeconds (etc.), toUTCString, and similar.
The constructor you're using does work in local time. That is, it constructs a Date object for midnight (because you're not providing hours, minutes, seconds, or milliseconds) local time in your timezone (because you've used new Date). If you want to get midnight UTC, you can do new Date(Date.UTC(+dateParts[2], dateParts[1] - 1, +dateParts[0])); instead. The only difference is the moment in time that the Date object represents (the given date at midnight local time vs. the given date at midnight UTC).