3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php // Settings $workStartHour = 9; $workStartMin = 0; $workEndHour = 17; $workEndMin = 30; $workdayHours = 8.5; $weekends = array('Saturday', 'Sunday'); $hours = 0; // Original start and end times, and their clones that we'll modify. $originalStart = new DateTime('2014-06-25 11:30:00'); $start = clone $originalStart; // Starting on a weekend? Skip to a weekday. while (in_array($start->format('l'), $weekends)) { $start->modify('midnight tomorrow'); } $originalEnd = new DateTime('2014-07-22 12:30:00'); $end = clone $originalEnd; // Ending on a weekend? Go back to a weekday. while (in_array($end->format('l'), $weekends)) { $end->modify('-1 day')->setTime(23, 59); } // Is the start date after the end date? Might happen if start and end // are on the same weekend (whoops). if ($start > $end) throw new Exception('Start date is AFTER end date!'); // Are the times outside of normal work hours? If so, adjust. $startAdj = clone $start; if ($start < $startAdj->setTime($workStartHour, $workStartMin)) { // Start is earlier; adjust to real start time. $start = $startAdj; } else if ($start > $startAdj->setTime($workEndHour, $workEndMin)) { // Start is after close of that day, move to tomorrow. $start = $startAdj->setTime($workStartHour, $workStartMin)->modify('+1 day'); } $endAdj = clone $end; if ($end > $endAdj->setTime($workEndHour, $workEndMin)) { // End is after; adjust to real end time. $end = $endAdj; } else if ($end < $endAdj->setTime($workStartHour, $workStartMin)) { // End is before start of that day, move to day before. $end = $endAdj->setTime($workEndHour, $workEndMin)->modify('-1 day'); } // Calculate the difference between our modified days. $diff = $start->diff($end); // Go through each day using the original values, so we can check for weekends. $period = new DatePeriod($start, new DateInterval('P1D'), $end); foreach ($period as $day) { // If it's a weekend day, take it out of our total days in the diff. if (in_array($day->format('l'), array('Saturday', 'Sunday'))) $diff->d--; } // Calculate! Days * Hours in a day + hours + minutes converted to hours. $hours = ($diff->d * $workdayHours) + $diff->h + round($diff->i / 60, 2);
Output for 5.3.0 - 7.2.0
Output for 5.2.0 - 5.2.17
Fatal error: Call to a member function modify() on a non-object in /in/kvYa2 on line 45
Process exited with code 255.
Output for 5.0.0 - 5.1.6
Fatal error: Class 'DateTime' not found in /in/kvYa2 on line 12
Process exited with code 255.
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_VARIABLE in /in/kvYa2 on line 13
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.4.1
Parse error: parse error, unexpected T_VARIABLE in /in/kvYa2 on line 13
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error in /in/kvYa2 on line 13
Process exited with code 255.