A
A
Alexander Lashchevsky2015-03-09 03:02:32
PHP
Alexander Lashchevsky, 2015-03-09 03:02:32

How to count dates (calculate age) in PHP (dates are stored in Unix Time)?

You need to calculate the age based on the specified date of birth. Date of birth information is contained in Unix Time.
I'm not strong in PHP, I just started editing my existing code to get what I need.
Let me give you an example just to understand:

$tpl->set( '{birthday}', langdate( "D M Y", $row['birthday'] ) );

Displays the date of birth in the {birthday} tag accessible to the CMS , i.e. takes the Unix Time value from the string birthday and converts it to human readable D ate M onth Y ear. To display age, I want to create an {age}
tag accessible to CMS and display age through it. I guess in PHP it should look something like this:
$tpl->set( '{age}', текущая дата - $row['birthday'] ) );

But how to do it - no idea ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill Saksin, 2015-03-09
@Alexanevsky

/** @var \DateTime $dateBirth */
$diff = (new \DateTime())->diff($dateBirth);
$formatted = sprintf("%d лет", $diff->y);

M
Mykola, 2015-03-09
@iSensetivity

function calculate_age($birthday) {
$birthday_timestamp = strtotime($birthday);
$age = date('Y') - date('Y', $birthday_timestamp);
if (date('md', $birthday_timestamp) > date('md')) {
$age--;
}
return $age;
}
echo calculate_age('1990-01-01');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question