Home > Software engineering >  Using Carbon in Laravel to extract and format a date and time from 20220916#120000
Using Carbon in Laravel to extract and format a date and time from 20220916#120000

Time:09-17

I'm getting a "date" value of "20220916#120000" and I have no idea how to use carbon to better format these to separate date and times.

I'm still learning, but this is what I have so far:

$weather_date = Carbon::createFromFormat('Ymd#His', $weather->features[0]->properties->date)->format('jS F Y h:i:s');

but the response I see when dd($weather_data) is 'Unexpected data found)

Could anyone please offer guidance/advise on what I need to do in order to have the date and time available in a way in which I can query against.

Thank you.

CodePudding user response:

There's more elegant solutions to this question, but the simplest solution is to replace the '#' with a '-'. It should be the fastest solution to the issue, but will require a comment for explanation

$dateStr = "20220916#120000";
$dateStr = \Str::replace("#", "-", $dateStr);
$weather_date = \Carbon\Carbon::createFromFormat('Ymd-His', $dateStr)->format('jS F Y h:i:s');

This is the more elegant solution to the problem; using regular expressions. It's easier to read, but the end result is the same.

$dateStr = "20220916#120000";
$dateTimeStr = preg_replace("/^(\d{4})(\d{2})(\d{2})#(\d{2})(\d{2})(\d{2})$/", '\1-\2-\3 \4:\5:06', $dateStr);
$weather_date = \Carbon\Carbon::parse($dateTimeStr)->format('jS F Y h:i:s');
  • Related