R
R
ronni102020-09-14 23:32:33
PHP
ronni10, 2020-09-14 23:32:33

How to get the difference of two dates in months?

So there are 2 dates. I need the difference between them in months, but the methods that I found do not work. The fact is that if there are 2 dates 2020-01-15 and 2020-02-13 , then for example the date_diff() function gives 0 because there are no 30 days between the dates, and I need the 1st of the next month - this is plus one month already. That is, 2020-01-31 and 2020-02-01 are already a difference of 1 month.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
SagePtr, 2020-09-15
@SagePtr

And what prevents you from mathematically calculating (Y2 * 12 + M2) - (Y1 * 12 + M1)?

A
Anton Shamanov, 2020-09-14
@SilenceOfWinter

see DatePeriod class

R
ronni10, 2020-09-15
@ronni10

$date1 = new DateTime("2020-01-15");
$date1->modify('first day of this month');
$date2 = new DateTime("2020-02-13");
$date2->modify('last day of this month');
$diff = $date1->diff($date2);
echo "difference " . $diff->m." months";

M
Maxim, 2020-09-15
@Tomio

Use the Carbon library :

$this_month = Carbon::parse('2019-07-05')->floorMonth(); // returns 2019-07-01
$start_month = Carbon::parse('2019-06-30')->floorMonth(); // returns 2019-06-01
$diff = $start_month->diffInMonths($this_month);  // returns 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question