简体   繁体   中英

how to get diff days between two dates if I consider every month is day 30 only

$start_date = Carbon::parse(date('Y-m-d', strtotime('2022-08-17')));
$end_date = Carbon::parse(date('Y-m-d', strtotime('2022-09-01')));
$diff = $start_date->diffInDays($end_date);

Days between these two dates is 15 , because aug is 31 day but in my case I consider every month is 30 day, so the difference should be 14

Carbon has a daysInMonth attribute which returns the number of days for a given date. So you could use that and do something like the following:

public function diffInDays($start_date, $end_date)
{
    $diff = $start_date->diffInDays($end_date);

    $daysInMonths = [$start_date->daysInMonth, $end_date->daysInMonth];

    foreach ($daysInMonths as $count) {
        if ($count >= 31) {
            $diff--;
        }
    }

    return $diff;
}

Then you would use the above as follows:

$start_date = \Carbon\Carbon::parse(date('Y-m-d', strtotime('2022-08-17')));
$end_date = \Carbon\Carbon::parse(date('Y-m-d', strtotime('2022-09-01')));

$diff = $this->diffInDays($start_date, $end_date);

This could be improved upon but the principle works as desired. The result is 14 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM