Home » Php » php – Need first and last day on a period datetime

php – Need first and last day on a period datetime

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m working with Carbon Period to get intervals of ‘N’ days between two dates.

In a iterations for each period I need to know how to get first and last day of each period.

E.g:

$period = CarbonPeriod::create('2019-10-01', '30 days', '2020-02-15');
// What I need is
// Period 1: from 2019-10-01 to 2019-10-31
// Period 2: from 2019-11-01 to 2019-11-30
// Period 3: from 2019-12-01 to 2019-12-31
// Period 4: from 2020-01-01 to 2020-01-31
// Period 5: from 2020-02-01 to 2020-02-15
How to&Answers:

I don’t think you can get the beginning/ending date of each period, but you can use a copy/setter to get the next day of the end period.

$period = CarbonPeriod::create('2019-10-01', '30 days', '2020-02-15');
$start = null;
foreach($period as $key=>$date) {
    if(!$start) {
        echo "Start 1 : ".$period->getStartDate()->toDateString(). " End : ".$date->toDateString()."\n";
        $start = $date->copy()->addDay();
    } else {
        echo "Start 2 : ".$start->toDateString(). " End : ".$date->toDateString()."\n";
    }
    $start = $date->copy()->addDay();
}
if($start->lt($period->getEndDate())) {
    echo "Start : ".$start->toDateString(). " End : ".$period->getEndDate()->toDateString()."\n";
}
//Start : 2019-10-01 End : 2019-10-01
//Start : 2019-10-02 End : 2019-10-31
//Start : 2019-11-01 End : 2019-11-30
//Start : 2019-12-01 End : 2019-12-30
//Start : 2019-12-31 End : 2020-01-29
//Start : 2020-01-30 End : 2020-02-15

Since 2020-01-30 – 2020-02-15 is not 30 days, it’s not created as another interval. You have to manually check for that add it as in the last few lines, if you want.

Answer:

First you should use 1 month as interval instead of 30 days:

$period = CarbonPeriod::create('2019-10-01', '1 month', '2020-02-15');

Then you can use endOfMonth() method to get your expected result:

$dates = [];

foreach ($period as $index => $date) {
    $dates[] = sprintf("Period %s: from %s to %s",
        $index + 1,
        $date->toDateString(),
        $period->getEndDate()->min($date->endOfMonth())->toDateString()
    );
}