我正在尝试获取两个给定日期之间每个月的星期六和星期日的数量。
例如:开始日期为 2015 年 7 月 5 日,结束日期为 2015 年 8 月 29 日,我需要在 7 月获得 7 个星期六和星期日,在 8 月获得 9 个。
到目前为止,直到上个月的第二个月我才获得值(value),即:没有获得八月。 怎么办?
代码
$countSat = 0;
$countSun = 0;
$start = new DateTime('05-07-2015');
$month = $start->format('n');
$end = new DateTime('29-08-2015');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
$i = 0;
foreach ($period as $dt) {
if ($month != $dt->format('n')) {
$results[$i] = $countSun + $countSat;
$i++;
$countSun = 0;
$countSat = 0;
}
if ($dt->format('N') == 7) {
$countSun++;
}
if ($dt->format('N') == 6) {
$countSat++;
}
$month = $dt->format('n');
}
echo '<pre>';
print_r($results);
最佳答案
您忘记在循环完成后添加结果。月份只会在循环内从 7 变为 8。 因此,上个月的天数被计算但从未添加。
$countSat = 0;
$countSun = 0;
$start = new DateTime('05-07-2015');
$month = $start->format('n');
$end = new DateTime('29-08-2015');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
$i = 0;
foreach ($period as $dt) {
if ($month != $dt->format('n')) {
$results[$i] = $countSun + $countSat;
$i++;
$countSun = 0;
$countSat = 0;
}
if ($dt->format('N') == 7) {
$countSun++;
}
if ($dt->format('N') == 6) {
$countSat++;
}
$month = $dt->format('n');
}
$results[$i] = $countSun + $countSat;
echo '<pre>';
print_r($results);
关于php - 日期时间 php 中上个月未生成的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33413878/