Skip to content
Advertisement

Uncaught Exception: DateTime::__construct(): Failed to parse time string

I’m using the function below to calculate the age (in years) of people from birthdays dates (in european format DD/MM/YYYY) that are stored as text in WordPress Advanced Custom Fields

function get_age($birthDate_old) {
    $birthDate = ($birthDate_old);
    return date_diff(new DateTime($birthDate), new DateTime('today'))->y;
}

In the majority of cases it works fine but in some cases I got the error below :

 Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (26/01/1958) at position 0 (2): Unexpected character in /home/XXXX/functions.php:99 Stack trace: #0 /home/XXXX/functions.php(99): DateTime->__construct('26/01/1958') #1 /home/XXXX/single.php(69): get_age('26/01/1958') #2 /home/XXX/wp-includes/template-loader.php(98): include('/home/XXX/...') #3 /home/XXX/wp-blog-header.php(19): require_once('/home/XXX/...') #4 /home/XXX/index.php(17): require('/home/monmaire/...') #5 {main} thrown in /home/XXXX/functions.php on line 99

Example of data that works fine : $age = get_age($birthday);

For $birthday value = 05/04/1946 it works fine but for $birthday value = 26/01/1958 I get the error above. I don’t undertand why as the data seems to me the same format in the 2 cases.

Do you have any clue why ?

Thanks. Regards.

Advertisement

Answer

I fix your function like this :

function get_age($birthDate_old) {
    return date_diff(
        DateTime::createFromFormat('d/m/Y', $birthDate_old), 
        new DateTime('today')
    )->y;
}

In your case your date is malformated since DateTime constructor doesn’t know if you pass a month or a day.

05/04/1946 is ok.

26/01/1958 is not ok because 26 represent month by default.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement