Wednesday, July 13, 2016

Countdown Timer / Days count in Business days code in PHP

<?php
$start = new DateTime(null, new DateTimeZone('America/New_York'));
$end = new DateTime('2017-05-05');
// 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');

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

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


echo $days; // 4?>

No comments:

Post a Comment