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

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.