Search code examples
javascriptjquerymomentjsdayjs

How to convert "dd/mm/yyyy" to ISO string in JavaScript


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.


Solution

  • 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());