Business Days To/Fro with PHP

The below example will help you with finding or setting a date to and/or fro using business days only. I needed this for a project I was working on and thought I would share.

<?php
function dateFromBusinessDays($days, $dateTime=null) {
  $dateTime = is_null($dateTime) ? time() : $dateTime;
  $_day = 0;
  $_direction = $days == 0 ? 0 : intval($days/abs($days));
  $_day_value = (60 * 60 * 24);

  while($_day !== $days) {
    $dateTime += $_direction * $_day_value;

    $_day_w = date("w", $dateTime);
    if ($_day_w > 0 && $_day_w < 6) {
      $_day += $_direction * 1; 
    }
  }

  return $dateTime;
}
// echo date("m/d/Y", dateFromBusinessDays(-7));
// echo date("m/d/Y", dateFromBusinessDays(15, time() + 3*60*60*24));
?>

<p>Business Days From Today: <?php echo date("m/d/Y", dateFromBusinessDays(15)); ?></p>

Enjoy

,

Comments are closed.