Reputation: 39
I want to loop start date and end date and generate dates by month. I use this code:
<?php
$start = (new DateTime($cust_data->date_sold));
$end = (new DateTime($cust_data->due_date));
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo "<tr>";
echo "<td>".$dt->format("m-d-Y")."</td>";
echo "</tr>";
}
Example date:
$start = '02-05-2018'
$end = '08-05-2018'
Result:
02-05-2018
03-05-2018
04-05-2018
05-05-2018
06-05-2018
07-05-2018
I want it to be like this:
03-05-2018
04-05-2018
05-05-2018
06-05-2018
07-05-2018
08-05-2018
But I don't know how.
Upvotes: 2
Views: 1120
Reputation: 474
Hope This will help you.
$s1 = date('d-m-Y', strtotime('02-05-2018' . ' + 1 day')); // Added one day to start from 03-05-2018
$s2 = date('d-m-Y', strtotime('08-05-2018'.' + 1 day')); //Added one day to end with 08-05-2018
$start = new DateTime($s1);
$end = new DateTime($s2);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo "<pre>".$dt->format("d-m-Y");
}
I have Added code as per d-m-y format. you can change as you needed.
Upvotes: 0
Reputation: 9265
An approach that uses only native DateTime
tools without having to parse the date again.
$start = (new DateTime($cust_data->date_sold))->modify('+1 day');
$end = (new DateTime($cust_data->due_date))->modify('+1 day');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("d-m-Y") . '<br>';
}
Upvotes: 1