php - 日期时间 php 中上个月未生成的值

标签 php datetime

我正在尝试获取两个给定日期之间每个月的星期六和星期日的数量。

例如:开始日期为 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/

相关文章:

sql - 当前时间戳 Redshift

sql-server - 从 SQL Server 中的日期时间字段中获取 'date'

php - 如何使用php通过图像名称调整文件夹中图像的大小?

python datetime 从现在开始添加秒数

javascript - 如何在 JavaScript 中比较日期

php - 当前时间戳与当前日期不同

mysql 数据库获取时间-温度值

php - 从存储查询php结果的数组var中获取值单个值

php - PHP中的所有错误路径

php - 让搜索查询更强大