How can I convert this date: 29/12/2022
where:
29 is day,
12 is month,
2022 is year,
to ISO string.
I tried this:
var dateStr = "29/12/2022";
var parts = dateStr.split("/")
var myDate = new Date(parseInt(parts[2]), parseInt(parts[1]) - 1, parseInt(parts[0]));
console.log(myDate.toISOString());
// 2024-05-11T22:00:00.000Z this is wrong
I was expecting different result.
CodePudding user response:
There is no need to parseInt
and to remove 1 to the month.
var dateStr = "29/12/2022";
var parts = dateStr.split("/")
var myDate = new Date(`${parts[2]}-${parts[1]}-${parts[0]}`);
console.log(myDate.toISOString());
CodePudding user response:
In my code usually I do something like this:
const dateStr = "29/12/2022";
const parts = dateStr.split("/");
const date = new Date(0); // It will set hours, minutes, and seconds to 0
date.setDate(parts[0]);
date.setMonth(parts[1]-1);
date.setFullYear(parts[2]);
console.log(date.toISOString());
CodePudding user response:
It may not be the most optimal way but you could do it this way as long as the month when it is a single digit is sent with zero at the beginning type: 01 -> January
let date = '29/12/2022';
let dateFormat = date[3] date[4] "-" date[0] date[1] "-
" date[6] date[7] date[8] date[9]
// 12-29-2022
let mydate = new Date(dateFormat)
// Thu Dec 29 2022 00:00:00 GMT-0500