How to convert a carbon into string, to take the date only?
Asked Answered
E

4

29

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

Euphrasy answered 5/6, 2018 at 4:39 Comment(4)
You can convert it with ->toDateString()Bingham
i've try this before make this thread and it cant solve this issue..Euphrasy
Possible duplicate of laravel need to display only date not time using the carbon classNonna
Carbon string formatting doc on how a carbon object can be read as a string in different formats.Perspicuity
G
45
$collection_item->created_at->format('Y-m-d');
Gurl answered 5/6, 2018 at 4:52 Comment(1)
Just to add to it - you can find some common formatting methods here carbon.nesbot.com/docs/#api-formattingDivide
D
26

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'];
Daley answered 3/2, 2019 at 22:37 Comment(0)
B
1

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

Beady answered 28/4, 2021 at 9:54 Comment(0)
H
1
 $carbon = Carbon::parse();

 echo (string)$carbon;
 // 2022-04-13 00:00:00

 $carbon->settings(['toStringFormat' => 'Y-m-d']);

 echo (string)$carbon;
 // 2022-04-13
Huggins answered 19/4, 2022 at 7:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.