S
S
Scuba2019-11-10 00:17:38
PHP
Scuba, 2019-11-10 00:17:38

How to count the number of affected months between two dates?

$date1 = strtotime('08.10.2019');
$date2 = strtotime('10.11.2019');

I somehow need to calculate how many months are actually involved between these dates. That is, the correct answer is: 2 , this is October and November.
But all the examples I found on the internet show 1 .
Point to the right train of thought, please.
The dumbest way that came to my mind is to loop from the first date to the second and write to the array array ('year' => 'month'), and then just count the number of elements, but this is expensive in terms of resources, if, for example, there will be 125 months.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2019-11-10
@targetologru

12 * (год2 - год1) + месяц2 - месяц1 + 1

D
Daria Motorina, 2019-11-10
@glaphire

I also looked for options, a lot of frightening)
I got it like this:

SELECT COUNT(
    	DISTINCT CONCAT(
            MONTH(date),
            YEAR(date)
        )
    ) 
    FROM `table_example` WHERE date IS NOT NULL

Takes a combination of month + year, counts the number of unique values

D
Dmitry Tarasov, 2019-11-10
@fast-je

They show everything correctly, there will always be 1 month, the difference between them is clear.
Do +1, xs.
Although here

$start    = (new DateTime('08-10-2019'))->modify('first day of this month');
$end      = (new DateTime('10-11-2019'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

$countMonth = 0;

foreach ($period as $dt) {
    echo $dt->format("Y-m") . "<br>\n";
    ++$countMonth;
}

echo $countMonth;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question