Reputation: 3276
Hi I have a function that checks to see if a user input string is a valid date. The user has to input the date in the format 25-January-2018
and it checks to see if it can be converted to the format 25-01-2018
. However when I test the function using a date where both the month and day are single digits then it returns false even though a valid date has been entered.
function validateDate($date){
$d = DateTime::createFromFormat('d-F-Y', $date);
return $d && $d->format('j-F-Y') === $date;
}
echo validateDate("03-February-2018"); //Returns false when it should be true
Upvotes: 0
Views: 47
Reputation: 3826
You should replace the j-F-Y
with d-F-Y
.
j
means 1 to 31 while d
means 01 to 31 then your two formats are different for the given date.
The following code works:
function validateDate($date){
$d = DateTime::createFromFormat('d-F-Y', $date);
return $d && $d->format('d-F-Y') === $date;
}
var_dump(validateDate("03-February-2018"));
Upvotes: 3
Reputation: 401
Use strtotime()
function better.
function validateDate($date){
$timestamp = strtotime($date);
$newDate = date('d-F-Y', $timestamp);
return ($timestamp && $newDate);
}
echo validateDate("03-February-2018");
Upvotes: 0
Reputation: 21
Your function could work :
return $d && $d->format('d-F-Y') === $date;
but if your want to check if it's a valid date use this :
DateTime::createFromFormat('d-F-Y', "03-February") // returns false if not a valid date & Object if valid
Upvotes: 0