我想在给定的月份和年份获得一周的日期范围(不包括星期六和星期日)。
例如:
$ month = 5; $ year = 2017;
期望输出:
First Week :
01-05-2017 to 05-05-2017
Second Week :
08-05-2017 to 12-05-2017
Third Week :
15-05-2017 to 19-05-2017
Fourth Week :
22-05-2017 to 26-05-2017
Fifth Week:
29-05-2017 to 31-05-2017
我在以下链接中尝试了脚本,但系统崩溃了。 http://sandbox.onlinephpfunctions.com/code/5f36a0af5401bfaa1847c8711f4fdbec67fed042
答案 0 :(得分:2)
这是一个小脚本,希望它有所帮助
$month = 3;
$year = 2017;
$date = new \DateTime("now");
$date->setDate($year, $month, 1);
$date->setTime(0, 0, 0);
//last day of the month
$maxDay = intval($date->format("t"));
//getting the first monday
$dayOfTheWeek = intval($date->format("N"));
if($dayOfTheWeek != 1) {
//print a partial week if needed
$diff = 8 - $dayOfTheWeek;
if($dayOfTheWeek <= 5) {
$from = $date->format("Y-m-d");
$diff2 = 5 - $dayOfTheWeek;
$date->modify(sprintf("+%d days", $diff2));
$to = $date->format("Y-m-d");
echo sprintf("from: %s to %s\n", $from, $to);
$diff -= $diff2;
}
$date->modify(sprintf("+%d days", $diff));
}
//iterate while we are in the current month
while(intval($date->format("n")) == $month) {
$from = $date->format("Y-m-d");
$date->modify("+4 days");
if(intval($date->format("n")) > $month) {
$date->setDate($year, $month, $maxDay);
}
$to = $date->format("Y-m-d");
$date->modify("+3 days");
echo sprintf("from: %s to %s\n", $from, $to);
}
输出:
from: 2017-05-01 to 2017-05-05
from: 2017-05-08 to 2017-05-12
from: 2017-05-15 to 2017-05-19
from: 2017-05-22 to 2017-05-26
from: 2017-05-29 to 2017-05-31
部分第一周输出
from: 2017-03-01 to 2017-03-03
from: 2017-03-06 to 2017-03-10
from: 2017-03-13 to 2017-03-17
from: 2017-03-20 to 2017-03-24
from: 2017-03-27 to 2017-03-31