S
S
Sergey Valitov2019-02-14 19:42:23
PHP
Sergey Valitov, 2019-02-14 19:42:23

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

3 answer(s)
I
Igor Deyashkin, 2019-02-14
@serejatoje

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

D
Dmitry Bay, 2019-02-14
@kawabanga

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

D
Deepin_OS, 2019-02-14
@Deepin_OS

Example:

$time = new DateTime('2018-08-07 10:30:00');// начало отсчёта
$time_off = new DateTime('2018-08-22 12:30:00');// конец отсчёта
$result = $time->diff($time_off);
echo "Между датами {$result->d} дн. {$result->h} час. {$result->i} мин.";

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question