0

Let's assume I have two dates in variables, like :

$dateFrom = '2021/07/20';
$dateTo = '2021/08/10';

I did that but it still doesn't get results:

$from = new \DateTime($dateFrom);
$to = new \DateTime($dateTo);

$interval = $to->diff($from);

$a = $interval->format('%m months');
dd($a); // result : 0 months

I need to calculate the number of months between $dateFrom and $dateTo. I need to get 2. Is there any way to get it?

Thanks

update: Mine is less than 60 days, less than 2 months. But how to complete 2 months

Miedkes
  • 589
  • 1
  • 5
  • 16
  • Does this answer your question? [How to calculate the difference between two dates using PHP?](https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Rahul_Mandhane Aug 10 '21 at 08:08
  • @Rahul_Mandhane I've seen this post..but it only got full month. It counts as 30 days as a month. Time I need to get the month by number of day but not enough 30 days – Miedkes Aug 10 '21 at 08:44

2 Answers2

1

u can use DateTime

$dateFrom = new DateTime('2021-07-20');
$dateTo = new DateTime('2021-08-10');

$interval = $dateTo->diff($dateFrom);

$interval->format('%m months');
Таня
  • 222
  • 3
  • 13
  • Thank you. But if my date is two strings, how should I handle it? `$dateFrom = '2021/07/20';` `$dateTo = '2021/08/10';` – Miedkes Aug 10 '21 at 08:25
  • @Miedkes, new DateTime(string of date) => new DateTime(2021-07-20), u need to transfer the string to the constructor of this object – Таня Aug 10 '21 at 08:28
  • The result when i follow you it returns 0.I edited the question.Can you help me – Miedkes Aug 10 '21 at 08:41
  • @Miedkes oh my god, it's not about the format, this format works too! count how many days are the difference between the dates? 21 day! therefore month 0 – Таня Aug 10 '21 at 08:48
  • Yes. I converted it, but the result is still 0 months . `date('Y-m-d', strtotime($dateTo));` – Miedkes Aug 10 '21 at 08:48
  • @Miedkes count days – Таня Aug 10 '21 at 08:49
  • Thank you. But I for example..dateFrom = "2021-07-01" and dateTo= "2021-08-30" I get is two months. But when $dateFrom = "2021-07-20" and $dateTo = "2021-08-10" it gets a month. But I want to get two months, that is July and August. So what to do? – Miedkes Aug 10 '21 at 08:59
  • @Miedkes , oh, ping me in telegram - tberendakova – Таня Aug 10 '21 at 09:51
1

This may help you:

    $dateFrom = '2021/07/20'; // Suppose dateFrom is older than dateTo
    $dateTo = '2021/08/10';
    $from = new DateTime($dateFrom);
    $to = new DateTime($dateTo);
    
    $monthsDiff = $to->format('m') - $from->format('m');
    $yearsDiff = $to->format('Y') - $from->format('Y');
    if ($monthsDiff < 0){
       $yearsDiff = $yearsDiff - 1;
    }
    echo ((($monthsDiff + 12) % 12) + 1) + $yearsDiff * 12;
cafertayyar
  • 1,012
  • 2
  • 5
  • 12