evil date subtraction problems

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
titaniumdoughnut
Forum Commoner
Posts: 33
Joined: Wed Jul 13, 2005 2:02 pm
Location: Manhattan

evil date subtraction problems

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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

Code: Select all

22 years, 6 days.
Technically, that's correct.
User avatar
titaniumdoughnut
Forum Commoner
Posts: 33
Joined: Wed Jul 13, 2005 2:02 pm
Location: Manhattan

Post by titaniumdoughnut »

Ok... if that's technically correct, what can I do to get the number I want out of it?!?

Thanks! :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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..
User avatar
titaniumdoughnut
Forum Commoner
Posts: 33
Joined: Wed Jul 13, 2005 2:02 pm
Location: Manhattan

Post 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;
}
?>
Post Reply