Skip to content

Instantly share code, notes, and snippets.

@krisidmisso
Created March 20, 2018 16:04
Show Gist options
  • Save krisidmisso/412213541ee79dc95673be8d8937a98e to your computer and use it in GitHub Desktop.
Save krisidmisso/412213541ee79dc95673be8d8937a98e to your computer and use it in GitHub Desktop.
Calculate working days without saturday, sunday and holidays
// based on https://gist.github.com/themattharris/1143040
function calc_working_days($from, $to, $normalise = true)
{
$_from = is_int($from) ? $from : strtotime($from);
$_to = is_int($to) ? $to : strtotime($to);
// normalising means partial days are counted as a complete day.
if ($normalise) {
$_from = strtotime(date('Y-m-d', $_from));
$_to = strtotime(date('Y-m-d', $_to));
}
$all_days = @range($_from, $_to, 60 * 60 * 24);
if (empty($all_days)) return 0;
$week_days = array_filter(
$all_days,
create_function('$t', 'return check_days($t);')
);
return count($week_days);
}
function check_days($t)
{
$holidays_db = Holiday::all()->toArray(); // holidays from db have just month and date
// get official holidays from db and build array to compare with $check
$dates = [];
array_map(function ($holiday) use (&$dates) {
array_push($dates, $holiday['month'] . '-' . $holiday['day']);
}, $holidays_db);
//day of week from requests - 0(sunday)-6(saturday)
$w = date("w", strtotime(" + {$t} seconds", 0));
// get day and month from timestamp of requests
$m = intval(date("m", strtotime(" + {$t} seconds", 0)));
$d = intval(date("d", strtotime(" + {$t} seconds", 0)));
$check = $m . '-' . $d;
return (!in_array($w, array(0, 6)) && !in_array($check, $dates));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment