Home > OS >  php 7.4 how to expect date format "ddmmYYYY"
php 7.4 how to expect date format "ddmmYYYY"

Time:06-15

I need to force the users to enter a date like this "ddmmYYYY" e.g : 14012022

The problem I'm facing is that I can't force this format just using this :

DateTime::createFromFormat('dmY', '14012022');

For example, DateTime::createFromFormat('dmY', '212022') for "02012022", it will not return false, although the date will still be wrong at the end.

Is there a way to force the user to pass the exact format that I expect, which is "ddmmYYYY" ?

I need 2 digits for the day, 2 digits for the month, and 4 digits for the year imperatively.

Thanks

CodePudding user response:

How about an addition check by converting the date back to string?

$inputDate = '212022';
$date = DateTime::createFromFormat('dmY', $inputDate);
$valid = $date && $date->format('dmY') == $inputDate;

Since the manual says,

Letters that are used for parsing numbers allow a wide range of values, outside of what the logical range would be.

So string like '32132022' is valid input for createFromFormat, the above method will help you to avoid such date string.

  • Related