Wie wandelt man einen Kohlenstoff in einen String um, um nur das Datum zu übernehmen?

Lesezeit: 1 Minute

Almaida Jodys Benutzeravatar
Almaida Jody

Ich habe eine Sammlung wie diese

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"
]

Wie nehme ich nur den „28.05.2018“? Kann mir jemand helfen, dieses Problem zu beheben? trotzdem danke

  • Sie können es mit konvertieren ->toDateString()

    – DevK

    5. Juni 2018 um 4:51

  • Ich habe es versucht, bevor ich diesen Thread erstellt habe, und es kann dieses Problem nicht lösen.

    – Almaida Jody

    5. Juni 2018 um 5:04

  • Ein mögliches Duplikat von Laravel muss mithilfe der Kohlenstoffklasse nur das Datum und nicht die Uhrzeit anzeigen

    – Machavity

    12. Juni 2018 um 15:55

$collection_item->created_at->format('Y-m-d');

Benutzeravatar von Mohammed Omer
Mohammed Omer

Ich bevorzuge das

$model_item->created_at->toDateString();

da alle Datumsfelder, die sich in befinden protected $dates array im Modal ist eine Art von \Carbon\Carbon.

Daher könnte der obige Code auf jedes Datumsfeld angewendet werden, sofern Sie es als Datum in deklariert haben $dates array im Modal wie folgt

// this includes created_at and updated_at by default so no need to add it 
protected $dates = ['approved', 'seen_at'];

Es ist auch möglich, Ihrem Modell automatisches Casting hinzuzufügen, zum Beispiel:

protected $casts = [
    'created_at' => 'date:Y-m-d',
    'updated_at' => 'datetime:Y-m-d H:00',
];

Hinweis: Ihr Kilometerstand kann je nach Laravel-Version variieren

https://laravel.com/docs/8.x/eloquent-mutators#date-casting

https://laravel.com/docs/8.x/eloquent-serialization#date-serialization

 $carbon = Carbon::parse();

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

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

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

1452400cookie-checkWie wandelt man einen Kohlenstoff in einen String um, um nur das Datum zu übernehmen?

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy