First, we need to convert the
Start by creating a new date.
let date = new Date('01-01-2020');
Then let's make the specific elements we are going to need and see what we start off with.
let day = date.getDate(); // 1 let month = date.getMonth(); // 0 let year = date.getFullYear(); // 2020
Huh? Why is the month 0? This is because
let month = date.getMonth() + 1; // 1
To add the leading zeroes to the day and month object we have several options, but the following is the cleanest and quickest.
In any case we have to convert the integer to a string.
let date = new Date('01-01-2020'); let day = date.getDate(); // 1 day = day.toString().padStart(2, '0'); // '01' let month = date.getMonth() + 1; // 1 month = month.toString().padStart(2, '0'); // '01' let year = date.getFullYear(); // 2020 let newDate = day + '-' + month + '-' + year; console.log(newDate); // '01-01-2020'
padStart function will only work on a string, hence we first convert the integer to a string.
padStart will append '0' to a maximum of two.
You can play around in this codepen demo.
Note: padStart unfortunately has no IE compatibility. 😭