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

TimeSocks's avatar

Why isn't this function to add days working?

Hi,

So I have function that takes in the start date of an event and the number of days its running for, and it then (should) add those days to the start date to produce an end date. Then I can return the results to my view, e.g.

Start date: 12-06-2015

Length: 4 days

End date: 16-06-2015

Output 12th - 16th June 2015

Here's the function:

function dateCalculator($date,$length)
    {

        $startDate = $date;
        
        $endDate = $date->addDays($length);

        if ($length > 0){
            return $dateString = $startDate->format('jS').' - '.$endDate->format('jS F Y');
        } else {
            return $dateString = '<span>'.$startDate->format('jS F Y').'</span>';
        }
    }

I don't think I'm adding the days correctly. I'm not getting any errors, but it simply outputs the end date the same as the start date. I have included Carbon at the top of my file.

0 likes
5 replies
mstnorris's avatar

@TimeSocks it doesn't look like $date is an instance of Carbon?

You need to change the $startDate assignment statement so that it parses the $date argument and creates an instance of Carbon for you to work with:

$startDate = Carbon::createFromFormat('Y-m-d', $date);

You may also want to validate that $length is a number (I'm not sure if it needs to be an integer).

TimeSocks's avatar

@mstnorris thanks for the quick reply.

I've tried your suggestion, and now it's throwing a 'trailing data' error:

ErrorException in compiled.php line 16363: Trailing data (View: /home/vagrant/Code/learning-laravel-5/resources/views/events/show.blade.php)

The date being passed in is the format 2015-08-16 00:00:00.000000 if that makes any difference.

mstnorris's avatar
Level 55

In that case adjust the ::createFromFormat accordingly...

Carbon::createFromFormat("Y-m-d H:i:s.u", $date);

Or, I think you can use:

Carbon::parse($date);
TimeSocks's avatar

@mstnorris Ok, I've changed the format to 'Y-m-d H:i:s.u' which matches AFAIC, but now it throws a 'Data missing' error...

EDIT:

Ah-ha! Carbon::parse($date) worked. Thanks very much.

mstnorris's avatar

That's great but on a side note, you shouldn't have received that error if you are passing in the correct data to begin with. In my opinion, createFromFormat is better as you can validate the input.

Please or to participate in this conversation.