Reputation: 3253
I trying to show the weekends between 2 dates in a formatted way.
For an example:
$start = strtotime(date('Y-m-d'));
$end = strtotime(2018-06-12);
for ($i = $start; $i <= $end; $i = strtotime("+1 day", $i)) {
//show weekends as
// saturday and sunday - march 24-25, 2018
// saturday - march 31, 2018
// sunday - april 1, 2018
// saturday and sunday - april 7-8, 2018
//.........
}
If you can see above i need to group the weekend and if the saturday and sunday falls in 2 different months show them separately.
Can someone please help me how to do this?
Upvotes: 0
Views: 54
Reputation: 23958
Here is one method which creates an array that I later can implode to get the string format you want.
The array is built on year, month, week and day.
Then it's just a matter of iterating and echoing.
$start = strtotime(date('Y-m-d'));
$end = strtotime("2018-06-12");
for ($i = $start; $i <= $end;) {
If(date("N", $i) == 6){
$arr[date("Y", $i)][date("F", $i)][date("W", $i)][date("l", $i)] = date("d", $i);
$i+= 86400;
$arr[date("Y", $i)][date("F", $i)][date("W", $i)][date("l", $i)] = date("d", $i);
$i+= 86400*6;
}Else If(date("N", $i) == 7){
$arr[date("Y", $i)][date("F", $i)][date("W", $i)][date("l", $i)] = date("d", $i);
$i+= 86400*6;
}Else{
$i+= 86400;
}
}
Foreach($arr as $year => $years){
Foreach($years as $month => $months){
Foreach($months as $week){
Echo implode(" and ",array_keys($week)) . " - " . $month . " " . Implode("-", $week) . ", ". $year . "\n";
}
}
}
Edit: forgot to output month.
Edit 2: changed the initial loop to not loop all days. Should make it slightly faster.
Edit 3: found a bug in the code. Corrected.
Upvotes: 1
Reputation: 1300
This should do:
$start = strtotime('2018-03-18');
$end = strtotime('2018-06-12');
for ($i = $start; $i <= $end; $i = strtotime("+1 day", $i)) {
if (date('w', $i) == 6) {
list ($currentDate, $currentMonth, $currentYear) = explode(' ', date('j F Y', $i));
$i = strtotime("+1 day", $i);
list ($nextDate, $nextMonth, $nextYear) = explode(' ', date('j F Y', $i));
if ($currentMonth == $nextMonth) {
echo 'Saturday and Sunday - ' . $currentMonth. ' ' . $currentDate . '-' . ($currentDate + 1) . ', ' . $currentYear . PHP_EOL;
continue;
}
echo 'Saturday - ' . $currentMonth . ' ' . $currentDate . ', ' . $currentYear . PHP_EOL;
echo 'Sunday - ' . $nextMonth . ' ' . $nextDate . ', ' . $nextYear . PHP_EOL;
continue;
} elseif (date('w', $i) == 0) {
echo 'Sunday - ' . date('F j, Y', $i) . PHP_EOL;
}
}
Upvotes: 0
Reputation:
Try this:
$start = strtotime(date('Y-m-d'));
$end = strtotime('2018-06-12');
for ($i = $start; $i <= $end; $i = strtotime("+1 day", $i)) {
$date = date('D Y-m-d N', $i);
$n = (int)date('N', $i);
if ($n > 5) {
echo $date . '<hr>';
}
}
date('N', $i) will give you number of the weekday(1-monday, 7-sunday)
And you check if its greater than 5(6 or 7) (Saturday or Sunday)
Upvotes: 0