How To Count Days Between Two Dates In PHP Excluding Weekends

Websolutionstuff | Jan-25-2023 | Categories : PHP

In this article, we will see how to count days between two dates in PHP excluding weekends. Here, we will learn to get day differences without weekends in PHP. Also, we will use the PHP date and time function and date interval function. S, you can easily count the day between two dates.

So let's see, PHP day difference without weekends, calculate days between two dates excluding weekends in PHP, and how to count days between two dates in PHP.

DateInterval: A date interval stores either a fixed amount of time in years, months, days, hours etc, or a relative time string in the format.

DatePeriod: A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.

Example:

In this example, we will use DateTimeDateInterval and DatePeriod.

<!DOCTYPE html>
<html>
<body>

<?php
$start = new DateTime('2022-01-01');
$end = new DateTime('2022-01-31');
// otherwise the  end date is excluded (bug?)
$end->modify('+1 day');

$interval = $end->diff($start);

// total days
$days = $interval->days;

// create an iterateable period of date (P1D equates to 1 day)
$period = new DatePeriod($start, new DateInterval('P1D'), $end);

// best stored as array, so you can add more than one
$holidays = array('2022-01-26');

foreach($period as $dt) {
    $curr = $dt->format('D');

    // substract if Saturday or Sunday
    if ($curr == 'Sat' || $curr == 'Sun') {
        $days--;
    }

    // (optional) for the updated question
    elseif (in_array($dt->format('Y-m-d'), $holidays)) {
        $days--;
    }
}


echo $days;
?>

</body>
</html>

Output:

20

 


You might also like:

Recommended Post
Featured Post
How To Encrypt And Decrypt String In Laravel 9
How To Encrypt And Decrypt Str...

In this article, we will see how to encrypt and decrypt a string in laravel 9. Using crypt helper, As we all know larave...

Read More

Mar-09-2022

Helper Function Example in Laravel 8
Helper Function Example in Lar...

Hello All, In this post we will see helper function example in laravel, Laravel provide in-buit global "hel...

Read More

Jun-22-2021

How To Send Mail Using Gmail In Laravel 9
How To Send Mail Using Gmail I...

In this article, we will see how to send mail using gmail in laravel 9. we will learn laravel 9 to send mail u...

Read More

Aug-03-2022

How to Run Specific Seeder in Laravel 8
How to Run Specific Seeder in...

In this example, we will learn how to run a specific seeder in laravel 8. If you want to run only one seeder in laravel...

Read More

Jan-19-2022