The problem
Need to convert date objects into human-readable formats
The solution
function formatDate(date, format = 'YYYY-MM-DD') {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}Parameters
dateDateDate object to format
formatstringFormat string
Put it to work
const now = new Date();
console.log(formatDate(now)); // "2024-01-15"
console.log(formatDate(now, 'YYYY/MM/DD HH:mm:ss')); // "2024/01/15 14:30:25"