On Laravel 11 site with php 8.3
I need to get only time(hours/minutes) from request time field with value
[time] => 2025-03-18T07:23:16.000Z
So I need result must be 07:23
I try to use formatting :
$time = Carbon::createFromFormat('Y-m-d H:i:s', $request->time);
But I got error :
Unexpected data found.
Trailing data
Which formatting have I to use ?
I recommend you use Carbon::parse
instead of Carbon::createFromFormat
.
$time = Carbon::parse('2025-03-18T07:23:16.000Z');
or you may use Y-m-d\TH:i:s.uO
format from this answer.
$time = Carbon::createFromFormat('Y-m-d\TH:i:s.uO', '2025-03-18T07:23:16.000Z');
I would usually use the parse
method with try catch just to be safe.
try {
$time = Carbon::parse($request->time);
} catch (\Exception $e) {
Log::error('Time cannot be parsed', ['time' => $request->time]);
return ;
}
After successfully parsing the time, simple use the format
method.
$time->format('H:i');
= "07:23"