Jump to content

JavaScript calculate age

Go to solution Solved by iamdavehart,

Recommended Posts

Site URL: https://violin-puma-x79z.squarespace.com/

Hi, 

I've been trying to get an age in years to show inside the code block but I cant get it to display the return value.

<!DOCTYPE html>
<html>
<body>

<p>Calculating age...</p>

<p id="howold"></p>

<script> 
today = new Date()
past = new Date(1993,03,07) // remember this is equivalent to 06 01 2010
//dates in js are counted from 0, so 05 is june

function calcDate(date1,date2) {
    var diff = Math.floor(date1.getTime() - date2.getTime());
    var day = 1000 * 60 * 60 * 24;

    var days = Math.floor(diff/day);
    var months = Math.floor(days/31);
    var years = Math.floor(months/12);

    var message = years + " years"

    return message
    }
   

a = calcDate(today,past)
console.log(a)

document.getElementById("howold").innerHTML = calcDate(date1,date2);
  </script>

</body>
</html> 

Any ideas?

Andrew

Link to comment
  • Replies 2
  • Views 459
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

  • Solution

you're not actually passing anything to your date function. date1 and date2 are the named arguments but you need to pass the function calcdate some real things, e.g. today and past variables.

// document.getElementById("howold").innerHTML = calcDate(date1,date2);
document.getElementById("howold").innerHTML = calcDate(today,past);

 

Dave Hart. Software/Technology Consultant living in London. buymeacoffee 

Link to comment
7 hours ago, iamdavehart said:

you're not actually passing anything to your date function. date1 and date2 are the named arguments but you need to pass the function calcdate some real things, e.g. today and past variables.

// document.getElementById("howold").innerHTML = calcDate(date1,date2);
document.getElementById("howold").innerHTML = calcDate(today,past);

 

Brilliant. Thank you so much. I was scratching my head at this for a while.

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.