1. 程式人生 > 其它 >php 獲取某個月的周次資訊

php 獲取某個月的周次資訊

通過年,月份獲取一個月的周次資訊

如果本月頭一天不是星期一,則向上一個月取週一,本月最後的幾天如果不能正好是一週,則忽略。

例如

2019-09月計算出來的結果

2016-08-29---2016-09-04
2016-09-05---2016-09-11
2016-09-12---2016-09-18
2016-09-19---2016-09-25

  

/*傳入年份($current_year)和月份($current_month)*/
//獲取某年某月的周次資訊
public static function getWeekData($current_year, $current_month)
{
$weekData = [];
$firstday = strtotime($current_year . '-' . $current_month . '-01');
$monday = $firstday - 86400 * (date('N', $firstday) - 1);//計算第一個週一的日期
for ($i = 1; $i <= 5; $i++) {
$start = date("Y-m-d", $monday + ($i - 1) * 86400 * 7);//起始週一
$end = date("Y-m-d", $monday + $i * 86399 * 7);//結束週日
if (date('m', $monday + $i * 86399 * 7) != $current_month) {
continue;
}
$data = [$start, $end];
array_push($weekData, $data);
}
return $weekData;
}