Convert an existing valid date format to another
We will do this without any external library. To convert January 25 2023
to 2023-01-25
, use this:
const d = new Date("January 25 2023");
const new_d = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
console.log(new_d) // 2023-1-25
// now date is 2023-1-25 , the month is missing a 0 before it
// lets fix it
const getMonth = d.toLocaleString("default", { month: "2-digit" });
const new_d_2 = d.getFullYear() + "-" + getMonth + "-" + d.getDate();
console.log(new_d_2) // 2023-01-25
Note that regular getMonth()
returns month from 0 for January, hence add 1 to it. But this is not needed for d.toLocaleString
.