'How to convert a carbon into string, to take the date only?
i have an collection like this
0 => array:4 [
"so" => "SO-1"
"product_name" => "EXTREME FORTE - BP"
"created_at" => Carbon @1527481346 {#628
date: 2018-05-28 04:22:26.0 UTC (+00:00)
}
"id" => "5b0b84027475aa1508002623"
]
how to take the "2018-05-28" only? can somebody help me to fix this problem? thank's anyway
Solution 1:[1]
$collection_item->created_at->format('Y-m-d');
Solution 2:[2]
i prefere this
$model_item->created_at->toDateString();
since all date fields that located in protected $dates array
in the modal is type of \Carbon\Carbon
.
so the above code could apply to any date field as long as you declared it as date in $dates array
in the modal
as follow
// this includes created_at and updated_at by default so no need to add it
protected $dates = ['approved', 'seen_at'];
Solution 3:[3]
It is also possible to add automatic casting to your model, for example :
protected $casts = [
'created_at' => 'date:Y-m-d',
'updated_at' => 'datetime:Y-m-d H:00',
];
Remark : your mileage may vary depending on your Laravel version
https://laravel.com/docs/8.x/eloquent-mutators#date-casting
https://laravel.com/docs/8.x/eloquent-serialization#date-serialization
Solution 4:[4]
$carbon = Carbon::parse();
echo (string)$carbon;
// 2022-04-13 00:00:00
$carbon->settings(['toStringFormat' => 'Y-m-d']);
echo (string)$carbon;
// 2022-04-13
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ziyad |
Solution 2 | |
Solution 3 | Wasabi |
Solution 4 | AlexSi |