1

I have this very simple piece of code that calculates the number of days between to given timestamps:

$timestamp1 = strtotime("2017-01-01");
$timestamp2 = strtotime("2017-01-05");

$timeDiff = abs($timestamp1 - $timestamp2);
$numberDays = $timeDiff/86400;
$numberDays = intval($numberDays);

It is working perfectly, but I am wondering if there is a way to exclude weekends in the calculation.

I have looked around online and found some alternative options but there is alot more code than what I have above so I am asking if there is an option with minimal code like my above example?

charlie
  • 415
  • 4
  • 35
  • 83

1 Answers1

2

This is what I use:

function createDateRangeArray($strDateFrom,$strDateTo)
{
    $aryRange=array();

    $iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),     
              substr($strDateFrom,8,2),substr($strDateFrom,0,4));

    $iDateTo=mktime(1,0,0,substr($strDateTo,5,2),     
            substr($strDateTo,8,2),substr($strDateTo,0,4));

    if ($iDateTo>=$iDateFrom)
    {
        if(date("w", $iDateFrom) != 0 and date("w", $iDateFrom) != 6) {
            array_push($aryRange,date('Y-m-d',$iDateFrom)); 
        }
        while ($iDateFrom<$iDateTo)
        {
            $iDateFrom+=86400; // add 24 hours
            if(date("w", $iDateFrom) != 0 and date("w", $iDateFrom) != 6) {
                array_push($aryRange,date('Y-m-d',$iDateFrom));
            }
        }
    }
    return $aryRange;
}
Pradeep
  • 9,667
  • 13
  • 27
  • 34
Chris
  • 4,672
  • 13
  • 52
  • 93