PHP 計(jì)算某一年某個(gè)月有幾周

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

代碼截圖如下:? ? ? ? ? ? ? ? ? ??

運(yùn)行結(jié)果(完美解決有些月份周不全的問題)


代碼片段如下


代碼具體如下:

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];

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容