业务需要,根据当前时间判断这个月每一周是几号到几号,比如这个月,第一周是1号到5号,第二周是6号到12号。。返回数组最好,不要年的,要月,俺是菜鸟,希望大神给予代码个思路...谢谢了
数据分析师2017-10-01 00:45:12
How does PHP determine the day of each week of each month? -PHP Chinese website Q&A-How does PHP determine the day of each week of each month? -PHP Chinese website Q&A
Let’s take a look and learn.
迷茫2017-03-09 09:30:45
/** * @param DateTime|int|string|null $date 可以是DateTime对象、时间戳、字符串形式的日期或者空值表示当前月份 * @return array [[1,2,3,4,5], ...] 分别表示这月每一周都是几号到几号 */ function getWeeksOfMonth($date=null){ if (is_numeric($date)){ $d = new DateTime(); $d->setTimestamp($date); $date = $d; } else if (is_string($date)){ $date = new DateTime($date); } else if ($date instanceof DateTime){ // nothing to do } else if (!$date){ $date = new DateTime(); } else { throw new InvalidArgumentException("Invalid type of date!"); } // 当前日期是在一个月里面是第几天 // j: 月份中的第几天,没有前导零 1 到 31 $dateDay = (int)$date->format('j'); // 这个月1号是星期几 // N: 1(表示星期一)到 7(表示星期天) $beginWeekDay = (int)$date->sub(new DateInterval("P" . ($dateDay - 1) . "D"))->format('N'); // 这个月最后一天是几号 // j 月份中的第几天,没有前导零 1 到 31 $endMonthDay = (int)($date->add(new DateInterval('P1M'))->sub(new DateInterval("P1D"))->format('j')); $weeks = []; $indexOfWeek = 0; $weekDay = $beginWeekDay; for ($day = 1; $day <= $endMonthDay; $day++){ if (!isset($weeks[$indexOfWeek])){ $weeks[$indexOfWeek] = []; } $weeks[$indexOfWeek][] = $day; $weekDay++; if ($weekDay > 7){ $weekDay = $weekDay - 7; $indexOfWeek++; } } // 只要一个星期里面的第一天和最后一天? foreach ($weeks as &$week) { $week = [$week[0], end($week)]; } return $weeks; } // 测试一下: foreach (getWeeksOfMonth() as $week){ echo implode(", ", $week) . "\n"; } // 输出:(今天是2017-03-08) // 1, 5 // 6, 12 // 13, 19 // 20, 26 // 27, 31 //
用到的日期时间API比较少,应该比较高效吧