If you are looking for custom logic to format JavaScript dates without using any libraries or plugins, look no further.
function formatDate(date, format) {
let result = format;
const datePartRegex = /YYYY|YY|MM|M|DD|D|HH|H|mm|m|ss|s/g;
return result.replace(
datePartRegex,
part => getDatePart(date, part)
);
}
function getDatePart(date, part) {
switch (part) {
case 'YYYY':
return date.getFullYear();
case 'YY':
return date.getFullYear().toString().substr(-2);
case 'MM':
return prefixWithZero(date.getMonth() + 1);
case 'M':
return date.getMonth() + 1;
case 'DD':
return prefixWithZero(date.getDate());
case 'D':
return date.getDate();
case 'HH':
return prefixWithZero(date.getHours());
case 'H':
return date.getHours();
case 'mm':
return prefixWithZero(date.getMinutes());
case 'm':
return date.getMinutes();
case 'ss':
return prefixWithZero(date.getSeconds());
case 's':
return date.getSeconds();
default:
return part;
}
}
function prefixWithZero(n) {
return n < 10 ? '0' + n : n;
}
There are three functions here:
- formatDate – a main function that you call with JavaScript Date object and format pattern
- getDatePart – helper function that contain logic for each part of the date format that you need
- prefixWithZero – helper function used in case number needs to be prefixed with ‘0’ (3 becomes 03, 10 stays 10)
Examples:
const date = new Date('2020/10/07');
console.log(formatDate(date, 'D.M.YYYY. HH:mm'));
// 7.10.2020. 00:00
console.log(formatDate(date, 'YYYY-MM-DD'));
// 2020-10-07
console.log(formatDate(date, "D. M 'YY"));
// 7. 10 '20
console.log(formatDate(date, 'YYYYMMDD'));
// 20201007
Use this function to format date in MySQL datetime format:
formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss');
If you need to extend or modify this logic to add new date parts, you would first modify datePartRegex in formatDate function to look for new pattern elements and then add logic to switch/case in getDatePart to replace this new pattern.
If you need to add logic for presenting the name of the month, check JavaScript toLocaleString function. Short example:
add MMMM to regex and extend switch/case logic with:
...
case 'MMMM':
return date.toLocaleString('default', { month: 'long' });
...
Hope this helps you with your projects and gets you creative with JavaScript dates.