Determine if the difference between two dates will be shown in months, weeks or days

38 Views Asked by At

I was wondering how to show the number of days, which is the difference of the start and end date. For example:

Using Carbon's diffInDays()

$diff = $start_date->diffInDays($end_date)

Now, let's say that the difference of $start_date and $end_end is 30 days. We all know that when using the Modulo operation(%) we can show that the difference between the two is 1 month since 30 is divisible by 30, it's the same as if the difference is 7 days, we can show it as 1 week.

But when the difference, for example is 35 days, 35%30 = 5, we have a remainder of 5 days. My problem is how can I show this as simple "35 days". Here's what I did so far.

$start_date = Carbon::parse($job->start_date);
$end_date = Carbon::parse($job->end_date)

$diff = $start_date->diffInDays($end_date);

if ($diff%30 == 0) {

  //show $result as 1 Month    

} else if ($diff%7 == 0) {

  //show $result as 1 Week  

} else {

  //show $result as $diff  

}

dd($result)

2

There are 2 best solutions below

1
blessing On

As you are dealing with an instance of Carbon and want to display the timestamp in a human readable format, you can do something like the below:

$start_date = Carbon::parse($job->start_date);
$end_date = Carbon::parse($job->end_date);
$start_date->diffForHumans($end_date, true); // 1 week

Depending on the timestamp it will return things like: 3 seconds ago, 1 week ago, 1 month ago and so forth.

Edit: the 2nd argument which i true removes the "ago" part of the returned string, so without it the returned value would be "1 week ago" instead of "1 week"

2
James Russel On

Finally got it to work, here's what I did

$start_date = Carbon::parse('2023-08-18');
$end_date = Carbon::parse('2023-09-15';

// Calculate the differences
$months = $start_date ->floatDiffInMonths($end_date );
$weeks = $start_date ->floatDiffInWeeks($end_date );

if (fmod($months, 1) == floatval(0)) {
   dd($months.' '.'Month/s');
} elseif (fmod($weeks, 1) == floatval(0)) {
   dd($weeks.' '.'Week/s');
} else {
   $days =  $start_date ->diffInDays($end_date );
   dd($days .' '.'Day/s');
}

the result will be "4 Week/s"