Below is a PHP function that calculates and displays the difference in days between two dates. This function will take two date strings as inputs, convert them to DateTime objects, and then calculate the difference in days.
Here’s how you can define and use the function:
<?php
// Calculate day difference
function calculateDayDifference($date1, $date2) {
// Create DateTime objects for the two dates
$datetime1 = new DateTime($date1);
$datetime2 = new DateTime($date2);
// Calculate the difference
$interval = $datetime1->diff($datetime2);
// Get the difference in days
$days_interval = $interval->days;
return $days_interval;
}
// Example usage
$date1 = "2023-07-01";
$date2 = "2023-07-15";
echo calculateDayDifference($date1, $date2);
?>
Explanation:
Creating DateTime Objects:
new DateTime($date1): This converts the first date string into a DateTime object.
new DateTime($date2): This converts the second date string into a DateTime object.
Calculating the Difference:
$datetime1->diff($datetime2): This calculates the difference between the two DateTime objects. The result is a DateInterval object.
Getting the Difference in Days:
$interval->days: This retrieves the difference in days from the DateInterval object.