php – Laravel – format date to store it on MySQL database-ThrowExceptions

Exception or error:

I am using Laravel and I have to get some dates and store it on MySQL database.

When I create the date like this:

$date_sol = Carbon::createFromFormat("Y-m-d H:i:s","2020-12-10 01:00:00");

The date is properly stored on the database. However, I have to get the date from an input.

I am trying to get the date and then format it like this:

$novaData = $request->input('solicitacao_data') . ' 15:16:17';
        $sol->data = Carbon::parse($novaData)->format("Y-m-d H:i:s");

However, I get the error:

DateTime::__construct(): Failed to parse time string (28/03/2020
15:16:17) at position 0 (2): Unexpected character

The error is at the line $sol->data = Carbon::parse($novaData)->format(“Y-m-d H:i:s”);

How do I make the formating conversion properly? I am new using Laravel. I am not sure about it.

How to solve:

For date format ‘d/m/Y’ try this.

Carbon::createFromFormat('d/m/Y', '22/02/2020')->toDateTimeString();

Similarly for date format Y-m-d try this

Carbon::createFromFormat('Y-m-d', '2020-02-22')->toDateTimeString();

output will be in format (Y-m-d H:i:s)

"2020-02-22 21:05:13"

Answer´╝Ü

Let’s say you receive something as input.
Well, ideally you should first sanitize it, to make sure you received a string that can be interpreted as a date. For that, I would suggest you to have a look there :
php date validation

So, you assign the input to a var and append a string representing some time to it:

$novaData = $request->input('solicitacao_data'). ' 15:16:17';

From here, the easiest is to convert the string into a timestamp. Which can be achieved this way:

$time = strtotime($novaData);

And now, you can use Carbon to format the date the way you want :

$sol->data = Carbon::createFromTimestamp($time)->format("Y-m-d H:i:s");

Leave a Reply

Your email address will not be published. Required fields are marked *