0

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.

padaleiana
  • 955
  • 1
  • 14
  • 23
Siqueira
  • 423
  • 1
  • 7
  • 29
  • format from input is `$novaData = '28/03/2020'` (used slash) but on carbon format is `Y-m-d` (used dash), try the with the same format (use dash separator) – Ata Mar 12 '20 at 19:52
  • ? I need to format that way: Y-m-d H:i:s .. that is the reason why I am formating, because I need this format. – Siqueira Mar 12 '20 at 20:03
  • `$novaData` value must `2020/03/28` on format `Y/m/d` not in `d/m/Y` (28/03/2020) – Ata Mar 13 '20 at 08:53

2 Answers2

3

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"
Hamid Ali
  • 875
  • 1
  • 8
  • 22
1

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");
groslouis
  • 86
  • 3
  • Except what does `strtotime` do with a d/m/y date? Nothing good. `echo Carbon\Carbon::createFromTimestamp(strtotime('12/01/2020'))->toDateString();` – miken32 Mar 12 '20 at 21:57