Reputation: 380
I need to check a string is match with some format, and i using DateTime::createFromFormat
to enforce it. but it got some bugs.
example i have an date: 8/15/2020, i try to parse it to datetime object with format "d/m/Y", then i print it in to other format:
DateTime::createFromFormat("d/m/Y", '8/15/2020')->format('d-m-Y')
// result: 08-03-2021
that is wreig, because i read in php.net https://www.php.net/manual/en/datetime.createfromformat.php they said: d: day (1->30), m: month (1->12), Y: year (2020)
But i got an strange result? how it work? or it is the bug?
thank you for your answer.
Upvotes: 0
Views: 1243
Reputation: 7683
I think the PHP manual is not correct.
The DateTime::getLastErrors() method generates a warning if the range for the day or month is exceeded. You can evaluate this. As an an example:
function DateTimeCreateFromStrictFormat($format, $input){
$dt = DateTime::createFromFormat($format, $input);
$errArr = DateTime::getLastErrors();
return $errArr['warning_count']+$errArr['error_count'] ? false : $dt;
}
$dt = DateTimeCreateFromStrictFormat("d/m/Y", '8/15/2020');
var_dump($dt); //bool(false)
$dt = DateTimeCreateFromStrictFormat("d/m/Y", '8/12/2020');
var_dump($dt); //object(DateTime)#2 (3) { ["date"]=> string(26) "2020-12-08 10:34:34.000000" ..
Upvotes: 1
Reputation: 61784
i try to parse it to datetime object with format "d/m/Y"
... it's not clear why you tried it like that. 8/15/2020
is clearly m/d/Y
. You need to parse it using the format it's actually written in.
You can output it again to d/m/Y
afterwards - that is a separate operation.
DateTime::createFromFormat("m/d/Y", '8/15/2020')->format('d-m-Y')
Upvotes: 1
Reputation: 1881
Your format is day/month/year
but there is no month 15
like the 8/15/2020
being given.
Did you mean 15/8/2020
?
Upvotes: 1