Awesome PHP Date Increment
I was trying to do a loop to find the weekend between two dates and something was really weird weird.
I need to follow some code, which I think should work fine.
$weekends = array();
// yyyy-mm-dd
$firstWeekend = '2015-09-04';
$lastWeekend = '2015-12-25';
$firstWeekendTime = strtotime($firstWeekend);
$lastWeekendTime = strtotime($lastWeekend);
$totalWeekends = 0;
for ($i = $firstWeekendTime; $i <= $lastWeekendTime; $i += (7 * 86400)) {
$totalWeekends++;
$weekends[date('Y-m-d', $i)] = array(
date('Y-m-d', $i),
date('Y-m-d', strtotime(date('Y-m-d', $i) . '+ 2 days'))
);
}
Eg. Output:
[2015-10-16] => Array
(
[0] => 2015-10-16
[1] => 2015-10-18
)
[2015-10-23] => Array
(
[0] => 2015-10-23
[1] => 2015-10-25
)
[2015-10-29] => Array
(
[0] => 2015-10-29
[1] => 2015-10-31
)
[2015-11-05] => Array
(
[0] => 2015-11-05
[1] => 2015-11-07
)
But this is not true, because the next weekend after 2015-10-23 is 2015-10-30. So the output should be as follows:
[2015-10-16] => Array
(
[0] => 2015-10-16
[1] => 2015-10-18
)
[2015-10-23] => Array
(
[0] => 2015-10-23
[1] => 2015-10-25
)
[2015-10-30] => Array
(
[0] => 2015-10-30
[1] => 2015-11-01
)
[2015-11-05] => Array
(
[0] => 2015-11-05
[1] => 2015-11-07
)
I finally did it by setting the default timezone and not striking out anything else, it worked.
date_default_timezone_set('America/Los_Angeles');
Can anyone understand why this increment is failing without a timezone? And the strangest thing is that it only fails around ~ 2015-10-25
I don't want other options to find the weekend ... I just want to understand why it acts like that.
Thank.
+3
source to share
1 answer
Just you need to change the loop condition for an added value loop like this
for ($i = $firstWeekendTime; $i <= $lastWeekendTime; $i = strtotime(date('Y-m-d', strtotime(date('Y-m-d', $i) . '+ 7 days'))))
instead
for ($i = $firstWeekendTime; $i <= $lastWeekendTime; $i += (7 * 86400))
0
source to share