I have two timestamps, which possibly can be any date and time. I want to get all minutes, which were on Sunday.
For a better understanding: The start and and end timestamp represent a date and time where an employee starts his work and finish his work. I want to get the minutes in sum, which the employee worked on a Sunday.
Here is my code:
function get_sunday_hours_from_timestamps($startTimestamp, $endTimestamp) {
$start = new DateTime();
$start->setTimestamp($startTimestamp);
$end = new DateTime();
$end->setTimestamp($endTimestamp);
$workedMinutes = 0;
$current = clone $start;
while ($current <= $end) {
$next = clone $current;
$next->modify('next day');
if ($current->format('w') == 0) {
$dayStart = ($current < $start) ? $start : $current;
$dayEnd = ($next > $end) ? $end : $next;
$diff = $dayEnd->diff($dayStart);
$minutes = $diff->days * 1440 + $diff->h * 60 + $diff->i;
$workedMinutes += $minutes;
}
$current = $next;
}
return $workedMinutes / 60;
// return $workedMinutes;
}
2
Answers
Thank you for your input. I was able to solve the problem. Hope this helps anybody else.
Warning: The solution below is highly inefficient and extremely slow, especially for large time periods as input. It only serves to illustrate a naive approach in an easily readable form. You can use this as a starting point, but use it wisely!
A very naive approach to your problem (count sunday minutes in a given time period) could be: Iterate over every minute in you period, check if that minute is on a sunday and count those minutes.
In PHP that could look like this:
But i’m sure you’ll be able to add many optimizations to that algorithm, e.g. you could check first if the given period includes any sundays at all…