Example:
$startDate
is Monday 2007-02-05 and $endDate
is Tuesday 2007-02-20. Then I want it to list:
Monday 2007-02-05
Monday 2007-02-12
Monday 2007-02-19
I looked at the PHP manual and found this to get all the days between two dates. But how to do it the way i want? PHP Code:
The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.
This works: $start_date = "2011-05-15"; $end_date = "2011-07-07"; $dates = array(); $stop = strtotime($end_date); for($i = strtotime($start_date); $i <= $stop; $i += 86400) $dates[] = date('Y-m-d', $i); @mocca 86400 is the number of seconds in one day.
Just use the date relative format: $date = new DateTime("last monday"); What would be the last Monday that passed. The strtotime function accepts a string, in the format "US English date", and parse it into a timestamp , making it possible to add dates, get specific days, and count other features.
$date1 = "2007-03-24"; $date2 = "2009-06-26"; $diff = abs(strtotime($date2) - strtotime($date1)); $years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); printf("%d years, %d months, %d ...
Rather than get all days and loop through them all, get the first Monday after the start date and then iterate 7 days at a time:
$endDate = strtotime($endDate);
for($i = strtotime('Monday', strtotime($startDate)); $i <= $endDate; $i = strtotime('+1 week', $i))
echo date('l Y-m-d', $i);
I needed the same and created a simple method.
public function getMondaysInRange($dateFromString, $dateToString)
{
$dateFrom = new \DateTime($dateFromString);
$dateTo = new \DateTime($dateToString);
$dates = [];
if ($dateFrom > $dateTo) {
return $dates;
}
if (1 != $dateFrom->format('N')) {
$dateFrom->modify('next monday');
}
while ($dateFrom <= $dateTo) {
$dates[] = $dateFrom->format('Y-m-d');
$dateFrom->modify('+1 week');
}
return $dates;
}
Then use it.
$dateFromString = '2007-02-05';
$dateToString = '2007-02-20';
var_dump($this->getMondaysInRange($dateFromString, $dateToString));
Result:
array (size=3)
0 => string '2007-02-05' (length=10)
1 => string '2007-02-12' (length=10)
2 => string '2007-02-19' (length=10)
Maybe it will be helpful for somebody.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With