Jump to content

Birthday function coming up short!


techiefreak05

Recommended Posts

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

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 :)

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;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.