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

dan3460's avatar

Create Carbon with time

I have the following time format coming from a spreadsheet:

"2:48 AM"

I'm updating a time field on a table and trying to use Carbon to create it:

    {
        $transferred = session()->get('timeStamp');
        // dd($transferred);
        return new Route([
            'key' => $row['route'],
            'departure' => Carbon::createFromFormat('g:i A', $row['departure_time']),
            'truck' => $row['truck_type']
        ]);
    }

With the format shown, I'm getting a "Data Missing" error from Carbon. If i take the "A" on the format i get a "Trailing Data" error message, so carbon is seeing that there is more to the string, but i suspect that is expecting more from the "A" mapping. In the meantime i created a function that calculates the time, but i think it will be more clear if i can do in carbon.

Thanks for the help guys,

0 likes
5 replies
vincent15000's avatar

Hello,

I don't know if it's possible because Carbon create a date and you have only a time.

If you look at the example below ...

$datetime = Carbon::createFromFormat('Y-m-d H:i:s.u', '2019-02-01 03:45:27.612584');

... you can try to adapt it to your problem.

$datetime = Carbon::createFromFormat('Y-m-d H:i AM', '2021-04-21 02:48 AM');

I don't have tested, perhaps you will have a problem with the AM.

dan3460's avatar

I do create another variable using just the time, but that time is in a 24 hrs format, example:

$other = Carbon::CreateFromFormat('H:i', "19:30");

That works.

Snapey's avatar

Your format is correct, as can be proved with tinker

>>> Carbon\Carbon::createFromFormat('g:i A','2:34 AM')
=> Carbon\Carbon @1618968840 {#3118
     date: 2021-04-21 02:34:00.0 Europe/London (+01:00),
   }
>>> 

So, if you are iterating over a number of rows, maybe one row has an invalid value, or an empty value?

dan3460's avatar

Wow, yes i'm iterating over a spreadsheet data. Did not think on testing with tinker. That gives me direction, thanks @snapey

Snapey's avatar

wrap it in a try catch and log the line and data when it fails

try {
     $departure = Carbon::createFromFormat('g:i A', $row['departure_time']);
} catch {
      Log::error('Could not convert departure time', $row);
      $departure = today();
}
return new Route([
            'key' => $row['route'],
            'departure' = $departure,
            'truck' => $row['truck_type']
        ]);

Please or to participate in this conversation.