日曆從星期日開始,通過確定每月第一天所在的星期,計算前後日期。
public function calendar(Request $request)
{
//獲取年
$year = $request->input('year', now()->year);
//獲取月份
$month = $request->input('month', now()->month);
$yearMonth = sprintf("%d-%s", $year, $month);
//獲取月份第一天所在的星期
$firstDayOfWeek = Carbon::parse("$yearMonth-01")->dayOfWeek;
//補全
$day = 0;
$calendar = [];
for ($i = 0; $i < 6; $i++) {
for ($j = 0; $j < 7; $j++) {
if ($firstDayOfWeek != 0 and $i == 0) {
//根據月初第一天所在的星期,計算出之前幾天的日子
$day = Carbon::parse("$yearMonth-01")->subDays($firstDayOfWeek - $j)->day;
$date = Carbon::parse("$yearMonth-01")->subDays($firstDayOfWeek - $j)->format("Y-m-d");
} else {
$day++;
$date = Carbon::parse("$yearMonth-01")->addDays($day - 1)->format("Y-m-d");
}
$calendar[$i][] = $date;
}
}
return $calendar;
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結