Search code examples
phpdateskipweekend

Calculate what the date will be based on startdate and value using PHP skip weekends


I have a startdate, let's say this is $startDate = 2012-08-01; and I have a variable that stores an INT value, lets say this is $value = 10;

I would like to calculate what the date would be from startdate + 10 days and skip weekends.

Using the above values the result would be 2012-08-15

How would this be done?


Solution

  • This is far from efficient, but who cares about that right when it is readable? :)

    <?php
    function calculateNextDate($startDate, $days)
    {
            $dateTime = new DateTime($startDate);
    
            while($days) {
                $dateTime->add(new DateInterval('P1D'));    
    
                if ($dateTime->format('N') < 6) {
                    $days--;
                }
            }
    
            return $dateTime->format('Y-m-d');
    }
    
    echo calculateNextDate('2012-08-01', 10); // return 2012-08-15
    

    DEMO

    What happens should be pretty easy to follow. First we create a new DateTime object using the date provided by the user. After that we are looping through the days we want to add to the date. When we hit a day in the weekend we don't subtract a day from the days we want to add to the date.