Web Hosting Forum | Lunarpages

Author Topic: Display current age using Javascript  (Read 2839 times)

Offline tcl

  • Spacescooter Operator
  • *****
  • Posts: 30
Display current age using Javascript
« on: April 26, 2013, 02:56:33 AM »
Hi,
I am looking for a javascript to display the current age of an individual. The website is for my granddaughter and I would like to be able to say, "Today I am 6 months, 3 days old". Is there an easy way to do this??

Offline scanman20

  • Senior Moderator
  • Über Jedi
  • *****
  • Posts: 1550
    • http://www.notonebit.com
Re: Display current age using Javascript
« Reply #1 on: April 26, 2013, 05:30:49 AM »
Try this:

Code: [Select]
<p>Hi I'm
<script>
    function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    console.log(today, birthDate, age, m);
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age + " years and " + m + " months old";
}
document.write(getAge('02-25-1973'));
</script>
 
Even a broken clock is right twice a day.
NotOneBit.com
MCSE - MCSA - MCP (<- unused since 2006!)

 

Share |