p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_php thread: Date of Birth code


Message #1 by "Srinivasan Prasanna" <sri_core@m...> on Tue, 28 May 2002 16:51:44 -0400
I am writing an application where the user in the form fills his date of 
birth and I should be calcualting his Age based on today's date. If you have 
any ideas pls let me know.
Thanks
Sri



_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp.

Message #2 by "Nikolai Devereaux" <yomama@u...> on Tue, 28 May 2002 14:17:27 -0700
How is the user entering the date?  The format of the input somewhat defines
how it should be calculated.

Message #3 by "Duncan Hutty" <duncanh@h...> on Tue, 28 May 2002 18:41:22 -0400
From memory late in the day:

$age = (mktime(0,0,0,$birthMonth, $birthDate, $birthYear)-time());

$age is measured in seconds. You can then calculate simply how many years,
months etc. that is.

Check
http://www.php.net/manual/en/ref.datetime.php to see whether I got it right
& learn the details. If you're doing (almost) any  project with PHP you'll
need to understand these functions.
Duncan Hutty


Message #4 by "Nikolai Devereaux" <yomama@U...> on Tue, 28 May 2002 16:02:31 -0700
The reason I would stay away from using time() and mktime() is because they
return offsets from Jan 1, 1970.

If the person was born before that date, you'll probably get screwy results.


$today     = getdate();
$thisyear  = $today['year'];
$thismonth = $today['mon'];
$thisday   = $today['mday'];


// A person's age is their birth year
// subtracted from the current year.
$years = $thisyear - $birthyear;

// However, if they haven't had their birthday
// yet this year, subtract a year from their age.

// More readable:
if($birthmonth > $thismonth)
{
    --$years;
}
else if($birthmonth == $thismonth)
{
    if($birthday > $thisday)
    {
        --$years;
    }
}



// Equivalent consolidated version:
if( ($birthmonth > $thismonth) ||
    (($birthmonth == $thismonth) &&
     ($birthday > $thisday)))
{
    --$years;
}



nik

Message #5 by sri_core@m... on Wed, 29 May 2002 20:30:32
The User is going to enter the birthday as MM/DD/YYYY. Do I need to submit 
this form and pass this as a string?
Thanks
Sri
Message #6 by "Nikolai Devereaux" <yomama@u...> on Wed, 29 May 2002 12:45:32 -0700
> The User is going to enter the birthday as MM/DD/YYYY. Do I need 
> to submit 
> this form and pass this as a string?

well, text fields are passed as strings anyway.

Try something like this:

<?php
//            1or2 digits/1or2 digits / 4 digits
$pattern = "/([\d]{1,2})\/([\d]{1,2})\/([\d]{4})/"

// $user_bday is the form input
if(! preg_match($pattern, $user_bday, $matches))
{
   error
}

$birthmonth = $matches[1];
$birthday   = $matches[2];
$birthyear  = $matches[3];


  ...


take care,

nik


  Return to Index