kargirwar
kargirwar

Reputation: 598

Unexpected DateTime behaviour in PHP

Here is a a simple piece of code where I am trying to convert a string into a DateTime object. Since the input string is invalid I expect the "Error" print.

<?php
$expiryDate = \DateTime::createFromFormat('d/m/Y', '01/02/20');
if (!$expiryDate) {
    echo "Error";
    return;
}
$expiryDate = $expiryDate->format('d/m/Y');
echo $expiryDate;
?>

However I get:

01/02/0020

How do I work around this?

Upvotes: 1

Views: 82

Answers (2)

Nick
Nick

Reputation: 147146

You can compare the result of date_create_from_format formatted to the parse format with the original date string, and if they don't match, there was an error:

$input_date = '01/02/20';
$format = 'd/m/Y';
$expiryDate = \DateTime::createFromFormat($format, $input_date);
if (!$expiryDate || ($expiryDate = $expiryDate->format($format)) != $input_date) {
    echo "Error" . PHP_EOL;
}
else {
    echo $expiryDate . PHP_EOL;
}

$input_date = '01/02/2020';
$format = 'd/m/Y';
$expiryDate = \DateTime::createFromFormat($format, $input_date);
if (!$expiryDate || ($expiryDate = $expiryDate->format($format)) != $input_date) {
    echo "Error" . PHP_EOL;
}
else {
    echo $expiryDate . PHP_EOL;
}

Output:

Error
01/02/2020

Demo on 3v4l.org

Upvotes: 1

glinda93
glinda93

Reputation: 8459

You can use preg_match to check if given date string is in valid format:

<?php
$dateString = '01/02/20';
$isValid = preg_match("/^\\d{2}\/\\d{2}\/\\d{4}$/", $dateString);
if (!$isValid) {
    echo "Error";
    return;
}
$expiryDate = \DateTime::createFromFormat('d/m/Y', $dateString);

if (!$expiryDate) {
    echo "Error";
    return;
}
$expiryDate = $expiryDate->format('d/m/Y');
echo $expiryDate;

Working code example: http://sandbox.onlinephpfunctions.com/code/11bd4863bd02b2ee9a02f490ca4e594dc0c33866

Upvotes: 0

Related Questions