Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use the padStart() method in JavaScript to insert leading zeroes to a date. Here's an example:

let today = new Date();
let year = today.getFullYear().toString();
let month = (today.getMonth()+1).toString().padStart(2, '0');
let day = today.getDate().toString().padStart(2, '0');

let formattedDate = year + '-' + month + '-' + day;
console.log(formattedDate); // Output: "2022-03-04"

In this example, we first create a new Date object and get the year, month, and day using various Date methods. Then we convert the year and month to strings and use the padStart() method to add leading zeroes to the month and day if needed. Finally, we concatenate the year, month, and day to create a formatted date string.