techiefreak05 Posted August 2, 2007 Share Posted August 2, 2007 i have the following code thats supposed to take a variable that holds a birthday, such as "03-24-1990",and show the age, such as "17" its not off by much, but it IS off by one year.. <?php function birthday($birthday){ list($month,$day,$year) = explode("-",$birthday); $month_diff = date("m") - $month; $day_diff = date("d") - $day; $year_diff = date("Y") - $year; if ($day_diff < 0 || $month_diff < 0){ $year_diff--; } return $year_diff; } ?> I use that one way, like this <?php $bday="03-24-1990"; birthday($bday); ?> That outputs as: 16, when it should output 17, because that's my birthday! Link to comment https://forums.phpfreaks.com/topic/62978-birthday-function-coming-up-short/ Share on other sites More sharing options...
btherl Posted August 2, 2007 Share Posted August 2, 2007 The logic here is faulty: if ($day_diff < 0 || $month_diff < 0){ $year_diff--; } Look at the following cases: 2000-01-01 2000-01-31 2000-02-01 2000-02-31 2000-08-01 2000-08-31 2000-09-01 2000-09-31 That should be enough to get the logic right Link to comment https://forums.phpfreaks.com/topic/62978-birthday-function-coming-up-short/#findComment-313637 Share on other sites More sharing options...
techiefreak05 Posted August 2, 2007 Author Share Posted August 2, 2007 So ... what do I do to fix it? Do I pass a different variable thru the function? Link to comment https://forums.phpfreaks.com/topic/62978-birthday-function-coming-up-short/#findComment-313638 Share on other sites More sharing options...
techiefreak05 Posted August 2, 2007 Author Share Posted August 2, 2007 Oh! I noticed the < 0 part. haha So how can I make it work, I got this script froma friend and he has no idea ... I chanegd the "< 0", to "< 1" still no change.. and what does $year_diff--; mean? Link to comment https://forums.phpfreaks.com/topic/62978-birthday-function-coming-up-short/#findComment-313656 Share on other sites More sharing options...
btherl Posted August 2, 2007 Share Posted August 2, 2007 Try this one out. I am not 100% convinced that it works, but it works for the test cases i've tried. function birthday($birthday){ list($month,$day,$year) = explode("-",$birthday); $month_diff = date("m") - $month; $day_diff = date("d") - $day; $year_diff = date("Y") - $year; if ($day_diff < 0) { $month_diff--; } if ($month_diff < 0){ $year_diff--; } return $year_diff; } Link to comment https://forums.phpfreaks.com/topic/62978-birthday-function-coming-up-short/#findComment-313719 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.