skip to Main Content

I am trying to determine the difference in months between the date the user is created and the current date.

However, if any of the date involves february it will result in the difference being returned to potentially be wrong.

Instead of returning difference of 1 it is returning 0.

Code

   $associated_user_created_at = Carbon::parse("2023-02-01 00:00:00");
    $currentDate = Carbon::parse("2023-03-01 23:59:59");
    error_log("H E L L O ");
    error_log($associated_user_created_at->format('d F Y'));
    error_log($currentDate->format('d F Y'));
    $diffInMonths = $associated_user_created_at->diffInMonths($currentDate, false);
    // $diffInMonths = $associated_user_created_at->diff($currentDate);
    error_log("****");
    error_log("Diff in months = " .$diffInMonths);
    dd($diffInMonths);

Output

H E L L O
01 February 2023
01 March 2023
****
Diff in months = 0

I have tried following the suggested solutions in this thread Incorrect diffInMonths laravel Carbon between Feb 1 and Mar 1 however it doesn’t solve the issue.

Project specifications

  • Php 7.4.25
  • Laravel 5

2

Answers


  1. Let’s assume you should not use Carbon::diffInMonths() for that because your version is outdated. Then for anniversary-style month diff, you can:

    $year = $associated_user_created_at->year;
    $month = $associated_user_created_at->month;
    $day = $associated_user_created_at->day;
    $diff = ($currentDate->year - $year) * 12 + $currentDate->month - $month - ($currentDate->day < $day ? 1 : 0);
    

    (Assuming currentDate >= associated_user_created_at)

    Login or Signup to reply.
  2. You can use this solution to get the number of different month using Carbon diffnInMonth

    $associated_user_created_at = Carbon::parse("2023-02-01 00:00:00")->format('Y-m-d');
    $currentDate = Carbon::parse("2023-03-01 23:59:59")->format('Y-m-d');
    $monthDiff = Carbon::parse($currentDate)->diffInMonths(Carbon::parse($associated_user_created_at));
    dd($monthDiff);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search