-1

I am new to PHP.

I want to show user's Age in numbers on user profile page.

I am recording user's Birth year in the database with this variable'birth_year'

I am not recording entire date of birth in datetime format.. I am only recording year like 1991

So currently if I want to display user's country then I write something like below

   <?php echo $user[country]; ?>

And that display's name of the country

Now similarly, I want to disply user's age.

So I am writting something like below but its working

<?php echo date('y') - $user[birth_year] ; ?>

So what php code should I write to get value of (Birth Year - Current Year)

Lokapedia
  • 105
  • 1
  • 4
  • 12

2 Answers2

1

You can get it by substract birthday date from current date.

Example -

  # object oriented
    $from = new DateTime('1970-02-01');
    $to   = new DateTime('today');
    echo $from->diff($to)->y;

    # procedural
    echo date_diff(date_create('1970-02-01'), date_create('today'))->y;
shubham715
  • 3,324
  • 1
  • 17
  • 27
0
<?= date('y') - $birth_year  ?> //only one line needed

try this code in php bracket

Here date('y') will return you current year (2016) and $birth_year is already having year of birth (Ex: 1994) so answer would be age