计算某一年某个月有几周,并获取每一周的起止日期以及起止时间戳
代码截图如下:
代码具体如下:
public static function getWeekIntervalByYearMonth($year_month = '', $format = 'Y-m-d')
{
$year_month = $year_month != '' ? $year_month : date('Y-m', time());
//php获取当前月份的所有天数
$total_day = date('d', strtotime("{$year_month} + 1 month -1 day"));
$date = [
'start' => $year_month . '-' . '01',
'end' => $year_month . '-' . $total_day,
];
//创建一个空数组
$weekInterval = [];
$i = 1;
$j = 1;
while (true) {
//计算第一天是周几
$day_number = date('N', strtotime($year_month . '-' . $i));
//每周第一天
$week_start_day = $i - ($day_number - 1) < 1 ? 1 : $i - ($day_number - 1);
//如果每周的第一天等于总天数,最后一天则等于总天数
if ($week_start_day >= $total_day) {
$week_start_day = $total_day;
}
//每周最后一天最大是总天数
$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));
//本周结束日期
$end_date = date($format, strtotime($year_month . '-' . $week_end_day));
//当周开始的时间 与结束时间
$weekInterval[] = [
'start_date' => $start_date,//本周起始日期
'end_date' => $end_date,//本周结束日期
'start' => strtotime($start_date),//本周起始时间戳
'end' => strtotime($end_date) + 86399,//本周结束时间戳
'week_th' => $j++//本周结束时间戳
];
$i = $i + 7;
if ($week_end_day == $total_day) { //如果本周的最后一天等于总天数跳出循环
break;
}
}
return [$date, $weekInterval];
}