特定の月と年の週の期間を見つけようとしています。日付は月曜日に開始し、日曜日に終了する必要があります。月の1日が日曜日(2011年5月以降)の場合、それが最初の要素である必要があります。
2011年5月
- 5月1日(日)
- 5月2日〜5月8日(月曜日〜日曜日)
- 5月9日〜5月15日(月曜日〜日曜日)
- 5月17日-Ma6y22(月曜日-日曜日)
- 5月23日〜5月29日(月曜日〜日曜日)
- 5月30日〜5月31日(月曜日〜火曜日)
2012年9月
- 9月1日-9月2日
- 9月3日-9月9日
- 9月10日-9月16日
- 9月17日-9月23日
- 9月24日-9月30日
この関数を使用して、2つの日付(つまり、月の1日と最終日)の週数を計算しています。
public function getWeekNumbers($startDate, $endDate)
{
$p = new DatePeriod(
new DateTime($startDate),
new DateInterval('P1W'),
new DateTime($endDate)
);
$weekNumberList = array();
foreach ($p as $w)
{
$weekNumber = $w->format('W');
$weekNumberList[] = ltrim($weekNumber, '0');
}
return $weekNumberList;
}
不思議なことに、1月の場合、[1、2、3、4、5]を期待しているときに、[52、1、2、3、4]の週番号が返されます。
週番号を取得したら、次のように使用します。
//The following loop will populate the dataset with the entire month's durations - regardless if hours were worked or not.
$firstDayOfMonth = date('Y-m-d', strtotime("first day of {$this->year}-{$monthName}"));
$lastDayOfMonth = date('Y-m-d', strtotime("last day of {$this->year}-{$monthName}"));
foreach ($this->getWeekNumbers($firstDayOfMonth, $lastDayOfMonth) as $key => $weekId)
{
// find first mоnday of the year
$firstMon = strtotime("mon jan {$this->year}");
// calculate how many weeks to add
$weeksOffset = $weekId - date('W', $firstMon);
$beginDays = $weeksOffset * 7;
$endDays = ($weeksOffset * 7) + 6;
$searchedMon = strtotime(date('Y-m-d', $firstMon) . " +{$beginDays} days");
$searchedSun = strtotime(date('Y-m-d', $firstMon) . " +{$endDays} days");
echo date("M d", $searchedMon) . " - " . date("M d", $searchedSun);
}
getWeekNumbers関数は期待している週の数値を返さないため、上記の関数の出力が次のようになるのは当然のことです。
- 12月24日〜12月30日(2012年)
- 1月2日-1月8日(2012)
- 1月9日-1月15日(2012)
- 1月16日-1月22日(2012)
- 1月23日-1月29日(2012)
1行目(12月24日から12月30日)は、昨年(2011年)ではなく、今年(2012年)の終わりであることに注意してください。
理想的には、次のように見せたい
何か案は?ありがとう!!