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

BernardK's avatar

How do I force a Laravel Carbon Object to change from ["date"]=> string(26) "YYYY-MM-DD HH:MM:DD" to ["date"]=> string(10) "YYYY-MM-DD"

I have $article['published_at'] object:

object(Carbon\Carbon)#197 (3) { ["date"]=> string(26) "2017-02-28 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }

I want to convert it to:

object(Carbon\Carbon)#197 (3) { ["date"]=> string(10) "2017-02-28" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }

I tried below, but the object reverts back to string(26). string(26) seems to be persistent

$article['published_at'] = Carbon::parse($article['published_at'])->format('Y-m-d');

After I do a var_dump of $article['published_at'], I get the same string(26) "2017-02-28 00:00:00.000000"

Any help is really appreciated.

0 likes
7 replies
BernardK's avatar

Sorry, I was not clear.

I have $article['published_at'] object:

object(Carbon\Carbon)#197 (3) { ["date"]=> string(26) "2017-02-28 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }

I want to convert it to:

object(Carbon\Carbon)#197 (3) { ["date"]=> string(10) "2017-02-28" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }
Olixr's avatar

@BernardK try $date->toDateString(); Same as echo $date->format('Y-m-d');

Snapey's avatar
Snapey
Best Answer
Level 122

When you dump the Carbon object, it is asked to present the object as a string. You are seeing the default format that the object returns when its __toString method is called.

From the docs; http://carbon.nesbot.com/docs/#api-formatting

You can also set the default __toString() format (which defaults to Y-m-d H:i:s) thats used when type juggling occurs.

Carbon::setToStringFormat('jS \o\f F, Y g:i:s a');

( this should be called once not per instance, but will affect all dates)

However, most would just format the date where it required by using the ->format() method or any of the other built in formats.

2 likes

Please or to participate in this conversation.