Skip to content

Instantly share code, notes, and snippets.

@arogachev
Last active March 9, 2016 10:55
Show Gist options
  • Save arogachev/0b01d4464d7bce898702 to your computer and use it in GitHub Desktop.
Save arogachev/0b01d4464d7bce898702 to your computer and use it in GitHub Desktop.
PHP - Get working (business) seconds in given time range

Example of usage:

$workingHours = DateTimeHelper::getWorkingSeconds('2016-02-01 08:00:00', '2016-02-09 15:00:00', 10, 19, ['01.01', '02.01'], 'd.m') / (60 * 60);
<?php
/**
* @author DrDeath72 https://github.com/DrDeath72
* @author arogachev <[email protected]>
*/
class DateTimeHelper
{
/**
* Get working (business) seconds in given time range
* @param string $fromTime
* @param string $toTime
* @param integer $fromWorkingHour
* @param integer $toWorkingHour
* @param array $holidays
* @param string $holidaysFormat
* @return integer
*/
public static function getWorkingSeconds($fromTime, $toTime, $fromWorkingHour, $toWorkingHour, $holidays, $holidaysFormat)
{
$startTimestamp = is_int($fromTime) ? $fromTime : strtotime($fromTime);
$endTimestamp = is_int($toTime) ? $toTime : strtotime($toTime);
$limitTimestamp = strtotime(date('Y-m-d 23:59:59', $endTimestamp));
$workingSeconds = 0;
$daySeconds = 60 * 60 * 24;
for ($timestamp = $startTimestamp; $timestamp < $limitTimestamp; $timestamp += $daySeconds) {
if (in_array(date($holidaysFormat, $timestamp), $holidays)) {
continue;
}
$day = date('Y-m-d', $timestamp);
$dayStartTimestamp = max(strtotime("$day $fromWorkingHour:00:00"), $startTimestamp);
$dayEndTimestamp = min(strtotime("$day $toWorkingHour:00:00"), $endTimestamp);
$workingSeconds += max(0, $dayEndTimestamp - $dayStartTimestamp);
}
return $workingSeconds;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment