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; | |
| } | |
| } |