How can PHP functions be customized to handle date conversions in both directions effectively?

To handle date conversions effectively in both directions, PHP functions can be customized by creating two functions: one to convert a date from a specified format to another format, and another to convert it back. This way, you can easily switch between different date formats without having to repeat the conversion logic each time.

function convertDate($date, $fromFormat, $toFormat) {
    $dateTime = DateTime::createFromFormat($fromFormat, $date);
    return $dateTime->format($toFormat);
}

function convertDateBack($date, $fromFormat, $toFormat) {
    $dateTime = DateTime::createFromFormat($fromFormat, $date);
    return $dateTime->format($toFormat);
}

// Example usage
$originalDate = '2022-01-01';
$newDate = convertDate($originalDate, 'Y-m-d', 'd/m/Y');
echo $newDate; // Output: 01/01/2022

$convertedDate = '01/01/2022';
$originalDate = convertDateBack($convertedDate, 'd/m/Y', 'Y-m-d');
echo $originalDate; // Output: 2022-01-01