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

martin182's avatar

Carbon createFromFormat not working

Hi, Im trying to get the last day of the week using Carbon. I am using the method createFromFormat. This is what I am doing (validatedData['date'] can be for example: 2019 04):

        $first_date = Carbon::createFromFormat('Y W', $validatedData['date'])->startOfWeek();

I get the following error:

message: "The format separator does not match ↵Trailing data"

0 likes
8 replies
Snapey's avatar

parse is complaining that your data is not in the right format. Is it definitely a four digit year?

tykus's avatar
tykus
Best Answer
Level 104

Something in this format will work:

(new Carbon)->setISODate(2019, 17)->startOfWeek();

In this case, you would need to separate $validatedData['date'] into two variables:

[$year, $week] = explode(' ', $validatedData['date']);

$first_date = (new Carbon)->setISODate($year, $week)->startOfWeek();
1 like
Snapey's avatar

we can only go by the error message. The data is not in the format you have told Carbon to expect

martin182's avatar

Hmm. That would be strange because I said in createFromFormat that the format is Y W. And the date has exactly the same format.

Cronix's avatar

Do what @tykus mentioned. You can test that it won't work the way you are trying it with

$date = '2019 06';

$parsed = Carbon\Carbon::createFromFormat('Y W', $date);

You'll get the same error due to the space. You need to separate them like Tykus was showing. If you had a complete date it would work.

Out of curiosity, what date do you expect it to give you? The first day of the 6th week of 2019 at midnight?

tykus's avatar

You cannot create a DateTime instance using the week number.

Please or to participate in this conversation.