format a date in to the format 'yyyy-mm-dd' in javascript

To format a date in JavaScript to the format 'yyyy-mm-dd', you can use the getFullYear(), getMonth() and getDate() methods of the Date object. Here's an example:

index.tsx
let date = new Date(); // current date
let year = date.getFullYear();
let month = ('0' + (date.getMonth() + 1)).slice(-2); // add leading zero if needed
let day = ('0' + date.getDate()).slice(-2); // add leading zero if needed
let formattedDate = year + '-' + month + '-' + day;
console.log(formattedDate); // output: '2021-08-17' (for example)
345 chars
7 lines

The slice() method is used to add leading zeros if needed, like in the case of February being the month and the day being the 2nd day.

gistlibby LogSnag