Search code examples
phpcodeigniterdate

Day difference without weekends


I want to count the total day difference from user input

For example when the user inputs

start_date = 2012-09-06 and end-date = 2012-09-11

For now I am using this code to find the diffeence

$count = abs(strtotime($start_date) - strtotime($end_date));
$day   = $count+86400;
$total = floor($day/(60*60*24));

The result of total will be 6. But the problem is that I dont want to include the days at weekend (Saturday and Sunday)

2012-09-06
2012-09-07
2012-09-08 Saturday
2012-09-09 Sunday
2012-09-10
2012-09-11

So the result will be 4

----update---

I have a table that contains date,the table name is holiday date

for example the table contains 2012-09-07

So, the total day will be 3, because it didn't count the holiday date

how do I do that to equate the date from input to date in table?


Solution

  • Very easy with my favourites: DateTime, DateInterval and DatePeriod

    $start = new DateTime('2012-09-06');
    $end = new DateTime('2012-09-11');
    // 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('2012-09-07');
    
    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; // 4