日期在PHP中的2个日期没有正确显示

时间:2018-05-01 17:48:57

标签: php datetime

以下代码并未显示05月份的输出作为输入,但如果日期范围较大则会显示正确的信息。

//Code for finding All the Dates between TWO Date
//Code for finding month between two Date
$startDate = new DateTime("2018-04-26");
$inputEndDate = new DateTime("2018-05-03");
$inputEndDate->modify('+1day');//for increasing the day by 1

//for counting the month
$monthInterval = new DateInterval('P1M');
$monthPeriod   = new DatePeriod($startDate, $monthInterval, $inputEndDate);
$monthCount = 0;

foreach ($monthPeriod as $date) {
$endDate = new DateTime(date("Y-m-t", strtotime($date->format('Y-m-d')))); 

//last day of the month

$endDate->modify('+1 day');//for increasing the day by 1
if ($inputEndDate < $endDate) {
    $endDate = $inputEndDate;
}


//var_dump($endDate);

$dateRange = new DatePeriod($startDate, new DateInterval('P1D'), $endDate);
$startDate = $endDate->add(new DateInterval('P1D'))->modify('-1 day');


echo "{$date->format('F')}-{$date->format('Y')}";
foreach($dateRange as $dateHeader){
    echo $dateHeader->format("Y-m-d");
}
$monthCount++;}

输出:

April-2018
2018-04-26
2018-04-27
2018-04-28
2018-04-29
2018-04-30

输出不会像输入一样显示另一个月的结果。

1 个答案:

答案 0 :(得分:0)

function get_dates_through_range($start, $end, $format = 'Y-m-d')
{
    $range = array();
    $interval = new DateInterval('P1D');

    $range_end = new DateTime($end);
    $range_end->add($interval);

    $period = new DatePeriod(new DateTime($start), $interval, $range_end);

    foreach($period as $date) {
        $range[] = $date->format($format);
    }

    return $range;
 }

get_dates_through_range('2018-04-30','2018-05-03')

输出

array(4) {
    [0]=>
    string(10) "2018-04-30"
    [1]=>
    string(10) "2018-05-01"
    [2]=>
    string(10) "2018-05-02"
    [3]=>
    string(10) "2018-05-03"
 }