Web Hosting Talk







View Full Version : Age Javascript


ballingtonma
12-17-2003, 11:45 AM
Hi, I require a script that will enable me to enter the date of birth in the body of the page, and the script in the head so that it will take the date of birth and change it in to an age. I will require multiple peoples ages on the page. I know what I have done as an example is totally wrong, but it will give you an idea of what i require.

<html>
<head>
<script language="JavaScript">
<!-- Begin
function age(day,month,year) {
document.write( day=" + day + ",month=" + month + ",year=" + year + " );
}
// End -->
</script>
</head>

<body>
<!-- Daves Profile -->
<b>DAVE</b>
Age:&nbsp;
<script language="JavaScript">
document.write(21,11,1986);
</script>
<br><br>
<!-- Johns Profile -->
<b>JOHN</b>
Age:&nbsp;
<script language="JavaScript">
document.write(02,10,1984);
</script>
</body>
</html>

For e.g. They would then appear like this:

DAVE
Age: 17

JOHN
Age: 19


Thanks In Advance,
Matt

Burhan
12-17-2003, 01:24 PM
Welcome to WHT :)

Change your function to this :


/* we don't need the month or day,
just the year */
function age(year) {
/* get a new date() object */
var temp = new Date();
/* get our year */
var cur_year = temp.getFullYear();
document.write( "Age: " + cur_year - year);
}


Then call it like this


<b>DAVE</b>
Age:
<script language="JavaScript">
age(1986);
</script>

digitok
12-17-2003, 01:37 PM
If my birthday is December, and it's currently May, it'll say I'm a year older than I am.

Just an observation :P

Burhan
12-17-2003, 01:41 PM
Well yeah -- didn't think about that :P But its not too difficult to add in there.

ballingtonma
12-17-2003, 03:19 PM
Thanks for the help, but I have put that in to my page and it is returning it as: NaN.:bawling:. And also I will require it to be exact and not say that you are like a year older then you are.
I would be very greatfull if you could help me get this working.

Thanks;)

brendandonhu
12-17-2003, 09:34 PM
If you want it to be exact, don't use javascript. It uses the computer's clock, which many people have set a year or two off by accident (yes this is more common than you might think, most people don't look at Windows calendar very often).

ballingtonma
12-19-2003, 10:28 AM
Any ideas how I can do it please...

brendandonhu
12-19-2003, 08:27 PM
Use a server-side language like PHP or Perl.