Skip to content
PHP Logo

How can developers use the Parameter pattern to define custom date formats in PHP?

Developers can use the Parameter pattern to define custom date formats in PHP by creating a function that accepts a date format string as a parameter. This allows developers to easily specify different date formats without having to modify the function itself.

php
function formatDate($date, $format) {
    return date($format, strtotime($date));
}

// Example of using the function with custom date formats
echo formatDate('2022-01-01', 'Y-m-d'); // Output: 2022-01-01
echo formatDate('2022-01-01', 'F j, Y'); // Output: January 1, 2022