tags:

views:

91

answers:

6

Hi

How can i calculate year from entering my age using php.

example:

i am entering my age as 24.

So that i need to get the year as 1985.

how this can be done.

thanks in advance

+6  A: 

If you knew simple math, you'd know that 2010 - 24 - 1 = 1985 or $year = date("Y") - $theirage - 1... But just giving an age does not accurately deduce what year they were born. For example:

If the date is December 30, 2010 and they say they're 24, you're still saying they were born in 1985 when chances are very, very high that they were actually born in 1986. You cannot rely on their age to give you their birth year.

EDIT If that wasn't very clear:

Today's date is June 16, 2010. So to be 24 years old, I would have needed to be born somewhere between June 17, 1985 and June 16, 1986. That's near half of the birthyears that would be 1985 and near half that would be 1986, causing a very high inaccuracy.

animuson
What about `$time = strtotime("-24 years");` ?
Russell Dias
@RussellDias: That still calculates 24 years ago from today's date. It causes the exact same issue.
animuson
Oh OK I get the problem now. Sorry just had to reread what you wrote =)
Russell Dias
Either ask the user their birthdate or birthyear will fix the issue.
RC
+1  A: 

To obtain the date 24 years ago, you can use strtotime:

$date = strtotime("-24 year");
echo date('%c', $date);
Sjoerd
A: 

PHP 5.3.0 also introduced a date_diff function as a part of the DateTime class.

nico
+1  A: 

With DateTime:

PHP > 5.2

<?php
       function getBirthYear($age) {
               $now = new DateTime();
               $now->modify("-" . $age . " years");
               return $now->format("Y");
       }

       echo getBirthYear(24);
?>

PHP > 5.3

<?php
       function getBirthYear($age) {
               $now = new DateTime();
               $now->sub(new DateInterval("P" . $age . "Y"));
               return $now->format("Y");
       }

       echo getBirthYear(24);
?>
RC
+1  A: 

Since you cannot give an exact year, it is better to specify a date range.

If you are 24 years old today (we usually round down, not round off), you were born between 17 Jun 1985 and 16 Jun 1986.

Methods of adding and subtracting dates have already been posted on this page.

Umang
A: 

WARNING: This is inacurate but its a try.

$yearBorn = round((((time()-($age*31556926))/31556926)+70));
$yearBorn = ($yearBorn>100)? "20".substr($yearBorn,1,2):"19".$yearBorn;
Babiker