Answer the question
In order to leave comments, you need to log in
How many days are there in the intersection of two dates?
Hello! Guys, who knows how to calculate the number of days at the intersection of two dates?
For example, there is an interval from 01/01/2019 to 01/15/2019. And the second date interval is 01/11/2019 and until 01/22/2019.
The dates from 11 to 15 January intersect here. As a result, 5 days.
Answer the question
In order to leave comments, you need to log in
The intersection of two date ranges is quite easy to get - it is the difference between the latest start and the earliest end of these periods.
/**
* Предполагается, что dateStart <= dateEnd. Если это не гарантируется, нужно их привести к такому виду внутри функции.
*/
function getIntersectDays(DateTime $dateStart1, DateTime $dateEnd1, DateTime $dateStart2, DateTime $dateEnd2) : int {
$intersectionEnd = min($dateEnd1, $dateEnd2);
$intersectionStart = max($dateStart1, $dateStart2);
if ($intersectionStart >= $intersectionEnd) return 0;
return (int)$intersectionStart->diff($intersectionEnd)->format('%a');
}
I know!
1) cast to one form (for example, int), and find out if the periods really intersect.
there may be that one is in the other, or they do not intersect at all, or they may even be the same.
2) take two dates in the middle and count the days - php.net/manual/ru/datetime.diff.php
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question