Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Populate Age Field based on Date of Birth Entered

Posted on 2007-11-13
8
Medium Priority
?
4,572 Views
Last Modified: 2012-08-13
I'm used to doing things on server side, so javascript is a little new to me.  Basically I have a need to take an existing text field 'Date Of Birth', in the format of MM/DD/YYYY, and upon entering this information have it populate another text field on the same page (Age, in the format of x Years, x Months, x Days).  Date should be calculated against current date, and the 'Age' field should populate immediately after the Date of Birth is entered (after tabbing to next field).  I've seen numerous scripts out there, but none that give me back the format that I want.  

A working code sample with HTML fields would be appreciated.  If possible I'd also prefer that the code be written in such a way that the user NOT get the 'To protect your security IE has restricted this webpage from running scripts that could access your computer' message.  

Thanks!
0
Comment
Question by:talphius
  • 4
  • 4
8 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 20278247
May I ask why you need the months and days - it is NOT trivial to calculate...


If Years are enough then

<script>
function showAge(yyyy,mm,dd, retirement_age) {

var d = new Date(yyyy,mm-1,dd,0,0,0)
alert(d)
var now = new Date();
now.setHours(0,0,0); // normalise
var bDay = new Date(now.getFullYear(),mm-1,dd)

if (bDay < now) alert('On your next birthday you will be '+(now.getFullYear()-d.getFullYear()+1))
else alert('You are '+(now.getFullYear()-d.getFullYear()))

var retire = new Date(d.getTime())
retire.setFullYear(retire.getFullYear()+retirement_age)
alert(retire)
alert('there are ' +(retire.getFullYear()-now.getFullYear()) +' years to your retirement'); // may be negative
}
showAge(1971,10,14,65)
</script>


0
 
LVL 5

Author Comment

by:talphius
ID: 20279209
It's for an form that a doctor's office is utilizing.  They frequently have pediatric patients and need to know the detail of how many years, months and, days the patient is as this data affects dosages for treatments, etc.  They are calculating this age now in their head, or based off the age that is given to them, but they want a more automated\accurate way to display this.

I could always do this server side once the form is submitted, but they'd like it to display on the form while they are filling it out

-T-
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 20280958
this looks right:
http://snippets.dzone.com/posts/show/623

Please note the months start at 0

<script>
// ---------------------------------------------------------------------------|
// qryHowOld                                                                  |
// Description: How old someone is in the format:                             |
// XXX Years XX Months X Weeks X Days                                         |
// Birth Date could be specified like Date.UTC(2002,8,16,17,42,0)             |
//                                                                            |
// Arguments:                                                                 |
//    varAsOfDate: as of date                                                 |
//    varBirthDate: birth date                                                |
//                                                                            |
function qryHowOld(varAsOfDate, varBirthDate)
   {
   var dtAsOfDate;
   var dtBirth;
   var dtAnniversary;
   var intSpan;
   var intYears;
   var intMonths;
   var intWeeks;
   var intDays;
   var intHours;
   var intMinutes;
   var intSeconds;
   var strHowOld;

   // get born date
   dtBirth = new Date(varBirthDate);

   // get as of date
   dtAsOfDate = new Date(varAsOfDate);

   // if as of date is on or after born date
   if ( dtAsOfDate >= dtBirth )
      {

      // get time span between as of time and birth time
      intSpan = ( dtAsOfDate.getUTCHours() * 3600000 +
                  dtAsOfDate.getUTCMinutes() * 60000 +
                  dtAsOfDate.getUTCSeconds() * 1000    ) -
                ( dtBirth.getUTCHours() * 3600000 +
                  dtBirth.getUTCMinutes() * 60000 +
                  dtBirth.getUTCSeconds() * 1000       )

      // start at as of date and look backwards for anniversary

      // if as of day (date) is after birth day (date) or
      //    as of day (date) is birth day (date) and
      //    as of time is on or after birth time
      if ( dtAsOfDate.getUTCDate() > dtBirth.getUTCDate() ||
           ( dtAsOfDate.getUTCDate() == dtBirth.getUTCDate() && intSpan >= 0 ) )
         {

         // most recent day (date) anniversary is in as of month
         dtAnniversary =
            new Date( Date.UTC( dtAsOfDate.getUTCFullYear(),
                                dtAsOfDate.getUTCMonth(),
                                dtBirth.getUTCDate(),
                                dtBirth.getUTCHours(),
                                dtBirth.getUTCMinutes(),
                                dtBirth.getUTCSeconds() ) );

         }

      // if as of day (date) is before birth day (date) or
      //    as of day (date) is birth day (date) and
      //    as of time is before birth time
      else
         {

         // most recent day (date) anniversary is in month before as of month
         dtAnniversary =
            new Date( Date.UTC( dtAsOfDate.getUTCFullYear(),
                                dtAsOfDate.getUTCMonth() - 1,
                                dtBirth.getUTCDate(),
                                dtBirth.getUTCHours(),
                                dtBirth.getUTCMinutes(),
                                dtBirth.getUTCSeconds() ) );

         // get previous month
         intMonths = dtAsOfDate.getUTCMonth() - 1;
         if ( intMonths == -1 )
            intMonths = 11;

         // while month is not what it is supposed to be (it will be higher)
         while ( dtAnniversary.getUTCMonth() != intMonths )

            // move back one day
            dtAnniversary.setUTCDate( dtAnniversary.getUTCDate() - 1 );

         }

      // if anniversary month is on or after birth month
      if ( dtAnniversary.getUTCMonth() >= dtBirth.getUTCMonth() )
         {

         // months elapsed is anniversary month - birth month
         intMonths = dtAnniversary.getUTCMonth() - dtBirth.getUTCMonth();

         // years elapsed is anniversary year - birth year
         intYears = dtAnniversary.getUTCFullYear() - dtBirth.getUTCFullYear();

         }

      // if birth month is after anniversary month
      else
         {

         // months elapsed is months left in birth year + anniversary month
         intMonths = (11 - dtBirth.getUTCMonth()) + dtAnniversary.getUTCMonth() + 1;

         // years elapsed is year before anniversary year - birth year
         intYears = (dtAnniversary.getUTCFullYear() - 1) - dtBirth.getUTCFullYear();

         }

      // to calculate weeks, days, hours, minutes and seconds
      // we can take the difference from anniversary date and as of date

      // get time span between two dates in milliseconds
      intSpan = dtAsOfDate - dtAnniversary;

      // get number of weeks
      intWeeks = Math.floor(intSpan / 604800000);

      // subtract weeks from time span
      intSpan = intSpan - (intWeeks * 604800000);

      // get number of days
      intDays = Math.floor(intSpan / 86400000);

      // subtract days from time span
      intSpan = intSpan - (intDays * 86400000);

      // get number of hours
      intHours = Math.floor(intSpan / 3600000);

      // subtract hours from time span
      intSpan = intSpan - (intHours * 3600000);

      // get number of minutes
      intMinutes = Math.floor(intSpan / 60000);

      // subtract minutes from time span
      intSpan = intSpan - (intMinutes * 60000);

      // get number of seconds
      intSeconds = Math.floor(intSpan / 1000);

      // create output string
      if ( intYears > 0 )
         if ( intYears > 1 )
            strHowOld = intYears.toString() + ' Years';
         else
            strHowOld = intYears.toString() + ' Year';
      else
         strHowOld = '';

      if ( intMonths > 0 )
         if ( intMonths > 1 )
            strHowOld = strHowOld + ' ' + intMonths.toString() + ' Months';
         else
            strHowOld = strHowOld + ' ' + intMonths.toString() + ' Month';

      if ( intWeeks > 0 )
         if ( intWeeks > 1 )
            strHowOld = strHowOld + ' ' + intWeeks.toString() + ' Weeks';
         else
            strHowOld = strHowOld + ' ' + intWeeks.toString() + ' Week';

      if ( intDays > 0 )
         if ( intDays > 1 )
            strHowOld = strHowOld + ' ' + intDays.toString() + ' Days';
         else
            strHowOld = strHowOld + ' ' + intDays.toString() + ' Day';

      if ( intHours > 0 )
         if ( intHours > 1 )
            strHowOld = strHowOld + ' ' + intHours.toString() + ' Hours';
         else
            strHowOld = strHowOld + ' ' + intHours.toString() + ' Hour';

      if ( intMinutes > 0 )
         if ( intMinutes > 1 )
            strHowOld = strHowOld + ' ' + intMinutes.toString() + ' Minutes';
         else
            strHowOld = strHowOld + ' ' + intMinutes.toString() + ' Minute';

      if ( intSeconds > 0 )
         if ( intSeconds > 1 )
            strHowOld = strHowOld + ' ' + intSeconds.toString() + ' Seconds';
         else
            strHowOld = strHowOld + ' ' + intSeconds.toString() + ' Second';

      }
   else
      strHowOld = 'Not Born Yet'

   // return string representation
   return strHowOld
   }
//                                                                            |
// qryHowOld                                                                  |
// ---------------------------------------------------------------------------|
alert(qryHowOld(new Date().getTime(), new Date(1972,9,31,17,42,0).getTime())); // 1972/10/31 !!!
alert(qryHowOld(new Date().getTime(), new Date(2004,1,29,0,0,0).getTime())); // 2004/02/29
</script>
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 5

Author Comment

by:talphius
ID: 20282489
This seems to display a security warning to the end user.  Is there any way to code this so that they are not required to click allow or add the sites to the trusted sites list?

Also, per my original request, how would this be integrated into a HTML form so that it auto populates an 'Age' field when 'DOB' is entered?

Thanks!
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 2000 total points
ID: 20283270
It should not give any alerts

Try this

<script>
// code lifted from http://snippets.dzone.com/posts/show/623
// ---------------------------------------------------------------------------|
// qryHowOld                                                                  |
// Description: How old someone is in the format:                             |
// XXX Years XX Months X Weeks X Days                                         |
// Birth Date could be specified like Date.UTC(2002,8,16,17,42,0)             |
//                                                                            |
// Arguments:                                                                 |
//    varAsOfDate: as of date                                                 |
//    varBirthDate: birth date                                                |
//                                                                            |
function qryHowOld(varAsOfDate, varBirthDate)
   {
   var dtAsOfDate;
   var dtBirth;
   var dtAnniversary;
   var intSpan;
   var intYears;
   var intMonths;
   var intWeeks;
   var intDays;
   var intHours;
   var intMinutes;
   var intSeconds;
   var strHowOld;
 
   // get born date
   dtBirth = new Date(varBirthDate);
 
   // get as of date
   dtAsOfDate = new Date(varAsOfDate);
 
   // if as of date is on or after born date
   if ( dtAsOfDate >= dtBirth )
      {
 
      // get time span between as of time and birth time
      intSpan = ( dtAsOfDate.getUTCHours() * 3600000 +
                  dtAsOfDate.getUTCMinutes() * 60000 +
                  dtAsOfDate.getUTCSeconds() * 1000    ) -
                ( dtBirth.getUTCHours() * 3600000 +
                  dtBirth.getUTCMinutes() * 60000 +
                  dtBirth.getUTCSeconds() * 1000       )
 
      // start at as of date and look backwards for anniversary
 
      // if as of day (date) is after birth day (date) or
      //    as of day (date) is birth day (date) and
      //    as of time is on or after birth time
      if ( dtAsOfDate.getUTCDate() > dtBirth.getUTCDate() ||
           ( dtAsOfDate.getUTCDate() == dtBirth.getUTCDate() && intSpan >= 0 ) )
         {
 
         // most recent day (date) anniversary is in as of month
         dtAnniversary =
            new Date( Date.UTC( dtAsOfDate.getUTCFullYear(),
                                dtAsOfDate.getUTCMonth(),
                                dtBirth.getUTCDate(),
                                dtBirth.getUTCHours(),
                                dtBirth.getUTCMinutes(),
                                dtBirth.getUTCSeconds() ) );
 
         }
 
      // if as of day (date) is before birth day (date) or
      //    as of day (date) is birth day (date) and
      //    as of time is before birth time
      else
         {
 
         // most recent day (date) anniversary is in month before as of month
         dtAnniversary =
            new Date( Date.UTC( dtAsOfDate.getUTCFullYear(),
                                dtAsOfDate.getUTCMonth() - 1,
                                dtBirth.getUTCDate(),
                                dtBirth.getUTCHours(),
                                dtBirth.getUTCMinutes(),
                                dtBirth.getUTCSeconds() ) );
 
         // get previous month
         intMonths = dtAsOfDate.getUTCMonth() - 1;
         if ( intMonths == -1 )
            intMonths = 11;
 
         // while month is not what it is supposed to be (it will be higher)
         while ( dtAnniversary.getUTCMonth() != intMonths )
 
            // move back one day
            dtAnniversary.setUTCDate( dtAnniversary.getUTCDate() - 1 );
 
         }
 
      // if anniversary month is on or after birth month
      if ( dtAnniversary.getUTCMonth() >= dtBirth.getUTCMonth() )
         {
 
         // months elapsed is anniversary month - birth month
         intMonths = dtAnniversary.getUTCMonth() - dtBirth.getUTCMonth();
 
         // years elapsed is anniversary year - birth year
         intYears = dtAnniversary.getUTCFullYear() - dtBirth.getUTCFullYear();
 
         }
 
      // if birth month is after anniversary month
      else
         {
 
         // months elapsed is months left in birth year + anniversary month
         intMonths = (11 - dtBirth.getUTCMonth()) + dtAnniversary.getUTCMonth() + 1;
 
         // years elapsed is year before anniversary year - birth year
         intYears = (dtAnniversary.getUTCFullYear() - 1) - dtBirth.getUTCFullYear();
 
         }
 
      // to calculate weeks, days, hours, minutes and seconds
      // we can take the difference from anniversary date and as of date
 
      // get time span between two dates in milliseconds
      intSpan = dtAsOfDate - dtAnniversary;
 
      // get number of weeks
      intWeeks = Math.floor(intSpan / 604800000);
 
      // subtract weeks from time span
      intSpan = intSpan - (intWeeks * 604800000);
 
      // get number of days
      intDays = Math.floor(intSpan / 86400000);
 
      // subtract days from time span
      intSpan = intSpan - (intDays * 86400000);
 
      // get number of hours
      intHours = Math.floor(intSpan / 3600000);
 
      // subtract hours from time span
      intSpan = intSpan - (intHours * 3600000);
 
      // get number of minutes
      intMinutes = Math.floor(intSpan / 60000);
 
      // subtract minutes from time span
      intSpan = intSpan - (intMinutes * 60000);
 
      // get number of seconds
      intSeconds = Math.floor(intSpan / 1000);
 
      // create output string
      if ( intYears > 0 )
         if ( intYears > 1 )
            strHowOld = intYears.toString() + ' Years';
         else
            strHowOld = intYears.toString() + ' Year';
      else
         strHowOld = '';
 
      if ( intMonths > 0 )
         if ( intMonths > 1 )
            strHowOld = strHowOld + ' ' + intMonths.toString() + ' Months';
         else
            strHowOld = strHowOld + ' ' + intMonths.toString() + ' Month';
 
      if ( intWeeks > 0 )
         if ( intWeeks > 1 )
            strHowOld = strHowOld + ' ' + intWeeks.toString() + ' Weeks';
         else
            strHowOld = strHowOld + ' ' + intWeeks.toString() + ' Week';
 
      if ( intDays > 0 )
         if ( intDays > 1 )
            strHowOld = strHowOld + ' ' + intDays.toString() + ' Days';
         else
            strHowOld = strHowOld + ' ' + intDays.toString() + ' Day';
 
      if ( intHours > 0 )
         if ( intHours > 1 )
            strHowOld = strHowOld + ' ' + intHours.toString() + ' Hours';
         else
            strHowOld = strHowOld + ' ' + intHours.toString() + ' Hour';
 
      if ( intMinutes > 0 )
         if ( intMinutes > 1 )
            strHowOld = strHowOld + ' ' + intMinutes.toString() + ' Minutes';
         else
            strHowOld = strHowOld + ' ' + intMinutes.toString() + ' Minute';
 
      if ( intSeconds > 0 )
         if ( intSeconds > 1 )
            strHowOld = strHowOld + ' ' + intSeconds.toString() + ' Seconds';
         else
            strHowOld = strHowOld + ' ' + intSeconds.toString() + ' Second';
 
      }
   else
      strHowOld = 'Not Born Yet'
 
   // return string representation
   return strHowOld
   }
//                                                                            |
// qryHowOld                                                                  |
// ---------------------------------------------------------------------------|
function getAge(theForm) {
  var d = theForm.dob.value;
  var parts = d.split('/');
  var dob = new Date(parts[2],parts[0]-1,parts[1],0,0,0);
  theForm.age.value=qryHowOld(new Date().getTime(), dob.getTime());
}
</script>
 
<form>
<input type="text" name="dob" value="">
<input type="button" onClick="getAge(this.form)" value=">>">
<input type="text" name="age"  value="">
</form>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 20283274
or

<form>
<input type="text" name="dob" value="" onBlur="getAge(this.form)" >
<input type="text" name="age"  value="">
</form>
0
 
LVL 5

Author Closing Comment

by:talphius
ID: 31409156
This worked perfectly - Thanks!
0
 
LVL 5

Author Comment

by:talphius
ID: 20286783
This worked perfectly - Thanks!
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

782 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question