To create a function that takes a Date object and a date format pattern from a variable (such as M/D/YYYY) and returns the date formatted according to that pattern, we can implement a custom formatting function. This will dynamically format the date based on the pattern provided in the variable.
function formatCustomDate(date, formatPattern) {
// Extract the components of the date
let day = date.getDate();
let month = date.getMonth() + 1; // getMonth() is zero-based, so add 1
let year = date.getFullYear();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
// Ensure all components are two digits if needed (e.g., 01, 02)
day = day < 10 ? ‘0’ + day : day;
month = month < 10 ? ‘0’ + month : month;
hours = hours < 10 ? ‘0’ + hours : hours;
minutes = minutes < 10 ? ‘0’ + minutes : minutes;
seconds = seconds < 10 ? ‘0’ + seconds : seconds;
// Replace tokens in the format pattern with actual date components
let formattedDate = formatPattern
.replace(‘DD’, day) // Day
.replace(‘D’, day) // Single-digit day (if format doesn’t want leading zeros)
.replace(‘MM’, month) // Month
.replace(‘M’, month) // Single-digit month
.replace(‘YYYY’, year) // Full year
.replace(‘YY’, year.toString().substr(2, 2)) // Last two digits of year
.replace(‘HH’, hours) // Hours (24-hour format)
.replace(‘mm’, minutes) // Minutes
.replace(‘ss’, seconds); // Seconds
return formattedDate;
}
// Example usage:
let currentDate = new Date();
let dateFormat = ‘M/D/YYYY’; // This can come from a variable
let formattedDate = formatCustomDate(currentDate, dateFormat);
log.debug(‘Formatted Date:’, formattedDate); // Expected output: e.g., “10/16/2024”