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

saadaan's avatar

Date format shuffling

Hi,

I have the upload-csv function available on one portal. The incoming date format is d-m-Y (31-12-2019). For storing in DB, I have to shuffle its order to make it Y-m-d. In addition, I have to check for sanity/correctness of the date as well. Can someone suggest a decent way to do this? I can do it in default PHP, but laravel should be more powerful, right?

Regards, Saad

0 likes
9 replies
ftiersch's avatar

I like to use Carbon for that but you can also use strtotime from PHP itself.

(new Carbon('32-12-2019'))->format('Y-m-d');

// or

(new Carbon('32-12-2019'))->toDateString();
saadaan's avatar

It's unhappy:

DateTime::__construct(): Failed to parse time string (32-12-2019) at position 8 (1): Unexpected character
Sinnbeck's avatar

I am pretty sure that no months have 32 days :)

saadaan's avatar

That's the sanity check I need; but in a more peaceful way, via some validation error :-)

ftiersch's avatar

Haha... god damnit... you're onto me! Should be a correct date of course :)

Otherwise:

Carbon::createFromFormat('d-m-Y', '31-12-2019')->toDateString();
saadaan's avatar

Yes, but how to run sanity checks then?

ftiersch's avatar

I would run the sanity checks with a validator.

So in a controller you could do this:

$this->validate(request(), [
    'datevalue' => 'required|date',
]);
1 like
saadaan's avatar

Yes, thanks. I am using the validator-after function, and the incoming data is via CSV import, not request. Can you help me a bit more to guide how to run this check inside validator-after function, as I don't seem to have a request variable in there?

Thanks, and sorry for perhaps a novice question!

        $validator->after(function ($validator) use ($importData_arr)
    {
        ....
    }

Please or to participate in this conversation.