Error: Argument 1 to diffInDays() must instance of Carbon – Code Example

Total
0
Shares

php-carbon throws the “Type error: Argument 1 passed to Carbon\Carbon::diffInDays() must be an instance of Carbon\Carbon, string given” when the arguments passed are anything different than year, month, day and timezone in diffInDays() function.

The definition of diffInDays() function is –

Carbon::createFromDate($year, $month, $day, $tz)

Code Example

Wrong Code – First of all let’s reproduce the error and then we will rectify it –

$date = "2022-08-29 11:41:00";
$datework = Carbon::createFromDate($date);
$now = Carbon::now();
$testdate = $datework->diffInDays($now);

This example will raise the TypeError: diffInDays() must be an instance of Carbon\Carbon because instead of passing year, date, month and timezone, we have passed the datetime string. This is not acceptable to createFromdate() function.

Correct Code

1. Using new Carbon()

$date = "2022-08-29 11:41:00";
$datework = new Carbon($date);
$now = Carbon::now();
$testdate = $datework->diffInDays($now);

The first method is to create a new instance of carbon date using constructor. You can pass the datetime string as argument to this constructor.

2. Using parse() function

$date = "2022-08-29 11:41:00";
$datework = Carbon::parse($date);
$now = Carbon::now();
$testdate = $datework->diffInDays($now);

Carbon parse() function is suitable to convert datetime string into carbon date object. You can now perform any date or time related operations on it.