Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate difference between two dates using Carbon and Blade

People also ask

How do you find the difference between two dates in carbon?

You can only use the diffInDays() function on a Carbon instance. You can create a new one by parsing the end date you're receiving. $end = Carbon::parse($request->input('end_date'));

How do you find the difference between two dates in flow?

To calculate a difference between two dates / times in Power Automate, you must combine multiple expressions. Calculate the number of ticks for each date, and then divide it by a number to get the desired unit. Start from 100 nanoseconds (1 tick) and divide it by a number big enough to get the days/hours/minutes.


You are not following the example from the Carbon Documentation. The method Carbon::createFromDate() expects 4 parameters: year, month, day and timezone. And you are trying to pass a formatted date string.

If you want to create a Carbon object from a formatted date string you can use the constructor of the class just like this:

$date = "2016-09-17 11:00:00";
$datework = new Carbon($date);

Or you can use the static Carbon::parse() method:

$date = "2016-09-17 11:00:00";
$datework = Carbon::parse($date);

For your purposes you can use the this full example:

$date = Carbon::parse('2016-09-17 11:00:00');
$now = Carbon::now();

$diff = $date->diffInDays($now);

And then in your Blade template:

<td> {{ $diff }} </td>

Blade Template

A shorter code

{{ $diff = Carbon\Carbon::parse($data->last_updated)->diffForHumans() }}

Result : 6 minutes ago


You code can be cleaned up and have the commented out code removed by doing:

<td>{{ $diff = Carbon\Carbon::parse($work['date'])->diffForHumans(Carbon\Carbon::now()) }} </td>

Carbon means you do not need to mix PHP Datetime and Carbon. Once you have the datetime as a Carbon, simply do this...

$comparisonTimeAsCarbon->diffAsCarbonInterval($theOtherTimeAsCarbon)

You can change diffAsCarbonInterval to diffAsSeconds, diffAsMinutes and many more.

diffForHumans is one of my faves.

Or, choose your own format with...

$comparisonTimeAsCarbon->diff($theOtherTimeAsCarbon)->format('%I:%S')

Carbon will even let you add text instead of a Carbon time, but, I recommend you use Carbon before you parse it, just in case.


Shortest way

We can directly write it in blade

<span>{{ \Carbon\Carbon::parse( $start_date )->diffInDays( $end_date ) }}</span>