计算 php 中两个日期之间的特定天数

Calculate number of specific day between two dates in php

我想找出两个日期之间特定天数的总数。我需要一个适合未来使用的解决方案,我想在未来使用任何开始日期和结束日期。

我的代码

$start_date       = new DateTime('2020/10/01');
$end_date         = new DateTime('2020/10/31'); 
$days = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
$diff = $start_date->diff($end_date, true)->days;
foreach ($days as $key => $value) {
   $number_of_days = intval($diff / 7) + ($start_date->format('N') + $diff % 7 >= $key+1);
   $result[$value] = $number_of_days;
}

结果

Array
(
    [Monday] => 5
    [Tuesday] => 5
    [Wednesday] => 5
    [Thursday] => 5
    [Friday] => 5
    [Saturday] => 5
    [Sunday] => 5
)

期待结果

Array
(
    [Monday] => 4
    [Tuesday] => 4
    [Wednesday] => 4
    [Thursday] => 5
    [Friday] => 5
    [Saturday] => 5
    [Sunday] => 4
)

首先:一周从星期日开始。

    $weekDays = ['Sunday', ...];

然后不要在循环中做一些不依赖于循环值的事情:

$numberOfDays = intval($diff / 7);
foreach ($weekDays as $weekDay) {
    $result[$weekDay] = $numberOfDays;
}
for ($weekDay = $startDate->format('N'), $endWeekDay = $endDate->format('N'); $weekDay != $endWeekday; $weekDay = ($weekDay + 1) % 7){
    $result[$weekday]++;
}

答案可能会有所不同,具体取决于您是否要包括开始日期和结束日期。

请检查下一个解决方案:

<?php
// create DateTime objects for date start & date end
$start_date       = new DateTime('2020/11/01');
$end_date         = new DateTime('2020/11/31'); 

// initialize counter array fro each day of week
$res = array(
    'Monday'   => 0,
    'Tuesday'  => 0,
    'Wednesday'=> 0,
    'Thursday' => 0,
    'Friday'   => 0,
    'Saturday' => 0,
    'Sunday'   => 0
);

// iterate dates between $start_date & $end_date
// if $end_date should not be included '<=' should be changed to '<'
while ($start_date <= $end_date) {
    $week_day = $start_date->format('l'); // get weekday for each date in interval
    $res[$week_day]++;                    // increase weekday counter
    $start_date->add(new DateInterval('P1D')); // iterate next day
}

print_r($res);

这里是直播代码PHPize.online