Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cameronmd's avatar

Difference between two carbon dates

Lets get straight to the point. In my form you select an end_date, by default it is:

\Carbon\Carbon::now()->addDays(7)

Then in my controller I have:

    $now = Carbon::now()->toDateString();
    $end_date = $request->input('end_date');

Now If I do this, these are the results

dd($now, $end_date);
"2016-03-29"
"2016-04-05"

Everything good so far I think? Now here's the problem.

    $lengthOfAd = $end_date->diffInDays($now);

And I get this error

Fatal error: Call to a member function diffInDays() on string

Any help is much appreciated, thanks in advance

0 likes
6 replies
joedawson's avatar
Level 18

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'));

No you should be able to compare them.

$now = Carbon::now();

$length = $end->diffInDays($now);
15 likes
vandyczech's avatar

Laravel has automatically convert so:

$now  = Carbon::now();
$end  = $request->input('end_date');

// show difference in days between now and end dates
print $now->diffInDays($end);
2 likes
jamieburnip's avatar

Is it not because you need to set the end date as a carbon instance?

$now = Carbon::now();

$end_date = Carbon::parse($request->input('end_date'));

$lengthOfAd = $end_date->diffInDays($now);
3 likes
sharjeel's avatar

You have to cast the date attribute in your model in order to automatically parse the dates

1 like
beertastic's avatar

@Tray2 Luckily, the internet is a long term solution for keeping answers. I was helped by this 2-year-old answer to a 7-year-old question. So, I guess that's why?

2 likes

Please or to participate in this conversation.