Forum Moderators: coopster
Is there a way to do the following;
convert_this_to_unix_timestamp($_POST['birthday_day'], $_POST['birthday_month'], $_POST['birthday_year']);
The point is that if i store it as a unix_timestamp, then i can do some math on it and return the users age instead of their birthday
Since im using this function for displaying a members age, if they are over 36 it will cause problems (becuase unix timestamp starts at 1970, so if someone was born before that, it returns a negative value, and my function calculates that. So if someone was born in 1960, my function says they are 10 years old.)
Here is my function
//put the post info into a string
$day = $_POST['birthday_day'];
$month = $_POST['birthday_mon'];
$year = $_POST['birthday_yr'];
$age = strtotime(''.$day.' '.$month.' '.$year.'');//now the function
function getAge($seconds) {
$now = time();
$then = $seconds;
$elapsed_time = $now - $then;
$one_year = '31556926';
$age = floor($elapsed_time / $one_year);
return $age;
}
//pass the variable through the function
$years_old = getAge($age);
It works great if the user is below 36, but if they are 37, there age will be displayed as 1+ for every year before 1970. So if they were born in 1965, they would be 5 years old.
Is there a simple tweak to my function that'll make this work, or is there something other then a unix timestamp i should use?
<?php
function get_age($dob_stamp)
{
$dob = getdate($dob_stamp);
$now = getdate(time());
$age = $now['year'] - $dob['year'];
$age-= (int)($now['mon'] < $dob['mon']);
$age-= (int)(($now['mon'] == $dob['mon']) && ($now['mday'] < $dob['mday']));
return $age;
}
?>
Hope this helps (you can find many more in online manual under mktime examples)
function calcAge($d) {
list [php.net]($by, $bmd) = explode [php.net]('-', $d, 2);
list($ty, $tmd) = explode('-', date('Y-m-d'), 2);
return $ty - $by - (($tmd < $bmd)? 1 :0);
}
list ($yyyy, $mm, $dd) = explode('-', date('Y-m-d'));
$yyyy -= 50;
$Person1 = "$yyyy-$mm-" . (sprintf [php.net]('%02d', $dd - 1));
$Person2 = "$yyyy-$mm-" . (sprintf('%02d', $dd + 0));
$Person3 = "$yyyy-$mm-" . (sprintf('%02d', $dd + 1));
?>
<html>
$Person1 Birthdate = '<?php print $Person1;?>'; // Age is <strong><?php print calcAge($Person1);?></strong> years old!<br />
$Person2 Birthdate = '<?php print $Person2;?>'; // Age is <strong><?php print calcAge($Person2);?></strong> years old!<br />
$Person3 Birthdate = '<?php print $Person3;?>'; // Age is <strong><?php print calcAge($Person3);?></strong> years old!<br />
</html>
You'll find that it can calc ages going back many years just fine. Go ahead, change the $yyyy -= to 500 and see ;)
You'll have to add your own edit checking, etc. to make sure you have a valid date before you pass it to this function. And the function expects the date in ISO format:
yyyy-mm-dd.