Page 1 of 1
evil date subtraction problems
Posted: Mon Sep 05, 2005 8:57 pm
by titaniumdoughnut
Ok, I'm trying to calculate an age on a given date. Like, if someone is born 11/08/1986(mm/dd/yyyy) how old will they be on 11/08/2008?
Here's the code I came up with:
Code: Select all
$age = gmmktime(0,0,0,11,08,2008) - gmmktime(0,0,0,11,08,1986);
$yearsold = floor($age/31536000);
$daysold = floor(($age % 31536000)/86400);
However there seems to be a problem with it! The result is that $yearsold contains 22 and $daysold contains 6. It should be 22 and 0.
So, like, what the heck? This is beyond my simple mental abilities.
Thanks,
Perry
Posted: Mon Sep 05, 2005 9:18 pm
by feyd
Code: Select all
$birth = gregoriantojd(11,8,1986);
$when = gregoriantojd(11,8,2008);
$days = $when - $birth;
$years = bcdiv($days,'365.24225',0);
$days = bcmod($days,'365.24225');
echo $years.' years, '.$days.' days.';
outputs
Technically, that's correct.
Posted: Mon Sep 05, 2005 9:28 pm
by titaniumdoughnut
Ok... if that's technically correct, what can I do to get the number I want out of it?!?
Thanks!

Posted: Mon Sep 05, 2005 9:43 pm
by feyd
simplest is to compare the month and day, if they are the same or larger, then you can simply get the difference between years, or however you want the information..
Posted: Mon Sep 05, 2005 10:03 pm
by titaniumdoughnut
That's what I was afraid of... I'll give it a shot.
edit:
it's inelegant and clunky, but it does the job. Right now I've got it calculating based on today's date, but it can easily be adapted for future dates, like before.
Code: Select all
<?php
$today[0] = (int)date("z");
$today[1] = (int)date("d");
$today[2] = (int)date("Y");
$yesterday[0] = date("z", mktime(0, 0, 0, 11, 8, 1986));
$yesterday[1] = 8;
$yesterday[2] = 1986;
$years = $today[2] - $yesterday[2];
if($today[0] < $yesterday[0]){
$f = 0;
}elseif($today[0] == $yesterday[0]){
$f = 1;
}elseif($today[0] > $yesterday[0]){
$f = 2;
}
if($f == 1){
$days = 0;
}elseif($f == 0){
$days = $today[0]+(365-$yesterday[0]);
$years = $years - 1;
}elseif($f == 2){
$days = ($today[0]+(365-$yesterday[0]))-365;
}
?>