? ? ? ? ? ? ? ? 計(jì)算某一年某個(gè)月有幾周,并獲取每一周的起止日期以及起止時(shí)間戳
代碼截圖如下:? ? ? ? ? ? ? ? ? ??


代碼具體如下:
public static function getWeekIntervalByYearMonth($year_month = '', $format = 'Y-m-d')
{
? ? $year_month = $year_month != '' ? $year_month : date('Y-m', time());
? ? //php獲取當(dāng)前月份的所有天數(shù)
? ? $total_day = date('d', strtotime("{$year_month} + 1 month -1 day"));
? ? $date = [
? ? ? ? 'start' => $year_month . '-' . '01',
? ? ? ? 'end' => $year_month . '-' . $total_day,
? ? ];
? ? //創(chuàng)建一個(gè)空數(shù)組
? ? $weekInterval = [];
? ? $i = 1;
? ? $j = 1;
? ? while (true) {
? ? ? ? //計(jì)算第一天是周幾
? ? ? ? $day_number = date('N', strtotime($year_month . '-' . $i));
? ? ? ? //每周第一天
? ? ? ? $week_start_day = $i - ($day_number - 1) < 1 ? 1 : $i - ($day_number - 1);
? ? ? ? //如果每周的第一天等于總天數(shù),最后一天則等于總天數(shù)
? ? ? ? if ($week_start_day >= $total_day) {
? ? ? ? ? ? $week_start_day = $total_day;
? ? ? ? }
? ? ? ? //每周最后一天最大是總天數(shù)
? ? ? ? $week_end_day = $i + (7 - $day_number) >= $total_day ? $total_day : $i + (7 - $day_number);
? ? ? ? //本周起始日期
? ? ? ? $start_date = date($format, strtotime($year_month . '-' . $week_start_day));
? ? ? ? //本周結(jié)束日期
? ? ? ? $end_date = date($format, strtotime($year_month . '-' . $week_end_day));
? ? ? ? //當(dāng)周開始的時(shí)間 與結(jié)束時(shí)間
? ? ? ? $weekInterval[] = [
? ? ? ? ? ? 'start_date' => $start_date,//本周起始日期
? ? ? ? ? ? 'end_date' => $end_date,//本周結(jié)束日期
? ? ? ? ? ? 'start' => strtotime($start_date),//本周起始時(shí)間戳
? ? ? ? ? ? 'end' => strtotime($end_date) + 86399,//本周結(jié)束時(shí)間戳
? ? ? ? ? ? 'week_th' => $j++//本周結(jié)束時(shí)間戳
? ? ? ? ];
? ? ? ? $i = $i + 7;
? ? ? ? if ($week_end_day == $total_day) { //如果本周的最后一天等于總天數(shù)跳出循環(huán)
? ? ? ? ? ? break;
? ? ? ? }
}
? ? return [$date, $weekInterval];
}