Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JamesMowatt's avatar

Carbon Date Diff without Weekends

Hi All,

I am looking for a way of cleanly getting the number of days between 2 dates while excluding weekends (and if possible extra dates). I am basically looking for the equivalent function of NETWORKDAYS in Google Sheets.

Thanks in Advance

James

0 likes
3 replies
tisuchi's avatar

There is a function in Carbon called, isWeekend(). You may be follow this-

$weekends = [];
$data = Model::get();

foreach($data as $d){
    $createdDate = $d->created_at;
    if($createdDate->isWeekend()){
        array_push($weekends, $createdDate);
    }
}

$totalWorkingDays = count($data) - count($weekends);

Source: http://carbon.nesbot.com/docs/

Alternatively, may be you can use a custom function in Laravel. Here is the function that can help you-

https://gist.github.com/quawn/8503445

jekinney's avatar

Off the top of my head (may need to parse carbon docs) you may have to loop through each day. Check if current looped day isWeekday() and add to counter. If not continue loop.

If Carbon does have a helper it probably just loops in the helper function anyways.

somnathsah's avatar
Level 3

Include in your file

use Carbon\Carbon;

And do like this

$dt = Carbon::create(2017, 4, 4);
        $dt2 = Carbon::create(2017, 4, 18);
        $daysForExtraCoding = $dt->diffInDaysFiltered(function(Carbon $date) {
            return !$date->isWeekend();
}, $dt2);
8 likes

Please or to participate in this conversation.