An user selects a specific month.
A function searches and designs a specific period.
e.g.
FROM the first day of month TO saturday
sunday - saturday
Until the final week.
sunday - the last day of month
e.g.
When the Parameter is 2022-11
Then
2022-11-01 - 2022-11-05
2022-11-06 - 2022-11-12
...
2022-11-27 -2022-11-30
Hoever , my code does not work correctly.
How should I fix it?
I think
date($arraySaturdayList[$k], strtotime("+1 day")
seems not work well.
private function month($start_date,$end_datel,holidays,
{
$arraySaturdayList = $this->makeSaturDayList($start_date,$end_date);
/*
$arraySaturdayList = Array
(
[0] => 2022-11-05
[1] => 2022-11-12
[2] => 2022-11-19
[3] => 2022-11-26
)
*/
for($i = $start_date,$k=0; $i <= $end_date ;$i++)
{
if($k+1 > sizeof($arraySaturdayList))
{
break;
}
$previousSunday = "";
$nextSunday = date($arraySaturdayList[$k], strtotime("+1 day"));
if($k > 0){
$previousSunday = date($arraySaturdayList[$k-1], strtotime("+1 day"));
}
}
//2nd week~ NOT the final
else if($k < sizeof($arraySaturdayList)){
//start_date should start from sunday . end_date should be ended in saturday.
$this->assignByWeekRange($previousSunday,$arraySaturdayList[$k]);
}
//the last week. (start from sunday end should be the last day of a month.)
else{
$this->assignByWeekRange($previousSunday,$end_date);
}
$k++;
}
}
The result was
S=2022-11-01E=2022-11-05
S=2022-11-05E=2022-11-12
S=2022-11-12E=2022-11-19
S=2022-11-19E=2022-11-26
My Answer:
It looks like there are a few issues in your code that need to be addressed. Here are some suggestions to fix it:
1. The loop condition should be `$i <= $end_date` instead of `$i < $end_date` to include the end date in the loop.
2. The `date()` function is used incorrectly. You should use `date('Y-m-d', strtotime('+1 day', strtotime($arraySaturdayList[$k])))` to add one day to the current Saturday date.
3. The logic for checking if it's the last week is incorrect. You should check if `$k == sizeof($arraySaturdayList) - 1` instead of `$k < sizeof($arraySaturdayList)`.
Here is the updated code:
php
private function month($start_date, $end_date, $holidays) {
$arraySaturdayList = $this->makeSaturDayList($start_date, $end_date);
for ($i = $start_date, $k = 0; $i <= $end_date; $i++) {
if ($k >= sizeof($arraySaturdayList)) {
break;
}
$previousSunday = "";
$nextSunday = date('Y-m-d', strtotime('+1 day', strtotime($arraySaturdayList[$k])));
if ($k > 0) {
$previousSunday = date('Y-m-d', strtotime('+1 day', strtotime($arraySaturdayList[$k - 1])));
}
if ($k < sizeof($arraySaturdayList) - 1) {
$this->assignByWeekRange($previousSunday, $arraySaturdayList[$k]);
} else {
$this->assignByWeekRange($previousSunday, $end_date);
}
$k++;
}
}
Make sure to adjust the code according to your specific requirements and data structures.
Rate this post
3 of 5 based on 3879 votesComments