Need help to produce data in PHP with help of functions
Like this
Ex.-1
Start Date : 12-04-2023
End Date : 30-06-2023
Output:
12-04-2023 to 30-04-2023 = 19 Days
May-2023
June-2023
Ex.-2
Start Date : 01-04-2023
End Date : 30-06-2023
Output:
April-2023
May-2023
June-2023
Ex.-3
Start Date : 01-04-2023
End Date : 12-06-2023
Output:
April-2023
May-2023
01-06-2023 to 12-06-2023 = 12 Days
Please see
Till now I have tried this code but Start period and End period are not as desired
<?php
// Define the start and end dates
$startDate = '2022-04-01';
$endDate = '2024-06-12';
// Function to format and display the results
function formatDateRange($startDate, $endDate) {
$start = new DateTime($startDate);
$end = new DateTime($endDate);
$result = '';
// Function to calculate and format the days in a month
function getDaysInMonth($startDate, $endDate) {
$start = new DateTime($startDate);
$end = new DateTime($endDate);
return $end->diff($start)->days + 1;
}
// Calculate the number of days from the start date to the end of the start month
$endOfStartMonth = new DateTime($start->format('Y-m-t')); // Last day of the start month
if ($endOfStartMonth >= $end) {
$result .= "{$start->format('d-m-Y')} to {$end->format('d-m-Y')} = " . getDaysInMonth($startDate, $endDate) . " Days<br>";
return $result;
} else {
$result .= "{$start->format('d-m-Y')} to {$endOfStartMonth->format('d-m-Y')} = " . getDaysInMonth($startDate, $endOfStartMonth->format('Y-m-d')) . " Days<br>";
$start = $endOfStartMonth->modify('first day of next month'); // Move to the first day of the next month
}
// Calculate and format the full months between start and end dates
$fullMonths = [];
$monthStart = (clone $start)->modify('first day of this month');
while ($monthStart <= $end) {
$monthEnd = (clone $monthStart)->modify('last day of this month');
if ($monthEnd > $end) {
$monthEnd = $end;
}
if ($monthStart->format('Y-m') != $monthEnd->format('Y-m')) {
$fullMonths[$monthStart->format('M/Y')] = getDaysInMonth($monthStart->format('Y-m-01'), $monthEnd->format('Y-m-t'));
} else {
$fullMonths[$monthStart->format('M/Y')] = getDaysInMonth($monthStart->format('Y-m-01'), $monthEnd->format('Y-m-d'));
}
$monthStart = (clone $monthEnd)->modify('first day of next month');
}
// Append full months to result
foreach ($fullMonths as $month => $days) {
$result .= "$month = $days Days<br>";
}
// Calculate the number of days from the start of the end month to the end date
if ($end->format('Y-m-01') < $end->format('Y-m-d')) {
$daysInEndMonth = getDaysInMonth($end->format('Y-m-01'), $end->format('Y-m-d'));
if ($daysInEndMonth > 0) {
$result .= "{$end->format('d-m-Y')} to {$end->format('d-m-Y')} = $daysInEndMonth Days<br>";
}
}
return $result;
}
// Display the formatted results
echo formatDateRange($startDate, $endDate);
?>