E
E
Eugene2019-01-15 09:47:15
PHP
Eugene, 2019-01-15 09:47:15

How to compare date formats in PHP?

Hello!
I am learning to work with VK API. The documentation contains the following field:
bdate / string
Date of birth. Returned in DMYYYY or DM format (if year of birth is hidden). If the entire date of birth is hidden, the field is missing from the response.
In a PHP script, I translate the date of birth into an age as best I could, like this:

// извлекаем из ответа его дату рождения 
$bdate = $user_info->response[0]->bdate;
// преобразуем дату рождения в возраст (лет)
$unixDate = strtotime($bdate);
$age = (int)((time() - $unixDate) / 31556926);

If the date comes in DMYYYY format, there is no problem, but if the date comes in DM format, then converting to age does not work anymore. I thought to compare "somehow" the date formats through if, but I did not find such solutions in the search. Type if the year has not come, then do not consider the user's age at all.
How correctly to process back such situation in PHP?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Bay, 2019-01-15
@vinegred

It's just...
Of course it doesn't work. And you can either store the age in years separately, and the date of birth separately. And that's how you solve your problem. I advise you to familiarize yourself with the php.net/manual/en/class.datetime.php library . It will solve many of your problems.
Since your date comes in two possible options, and comes from a trusted source, then consider something like this:

$date = '01.10.2001';
        $dateType = count( explode('.',$date));

        if ( $dateType=== 3) { // работаем как с полноценной

        } elseif ($dateType=== 2) { // работаем как с срезанной
            
        } else {// дата не опознана
            
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question