Calculate Age using CMS date field - Custom code

Hi!

I am tryin to get the age of the owners, I have a included a date field called “Birthday” and I wanted to calculate the age for each Owner its birthday.

What I did:

  • Add in “Before tag” the code
  • Add embed code in the page the same code
<script>
const anos = Birthday
function calculateAge(date) 
{
  const now = new Date();
  const diff = Math.abs(now - date );
  const age = Math.floor(diff / (1000 * 60 * 60 * 24 * 365)); 
  return age
}
calculateAge(anos) 
</script>

image

The result does not appear anywhere.

Could anyone help me on that? Basically to bring the results of Javascript into the page.

Here the link of the project:
https://preview.webflow.com/preview/2sami?utm_medium=preview_link&utm_source=designer&utm_content=2sami&preview=fe421a26feb7a834eca6c9ae79b44de2&pageId=627cd36ad95f1017d0b1ccb7&itemId=627cd386d87d48e3fabf221d&workflow=preview

Thanks!!

Hi @victorpaolo,

Welcome to the forum!

Try replacing it with this code:

<script>
const anos = new Date("+Add Field - Birthday HERE");
const now = new Date();
const diff = now-anos;
const age = Math.floor(diff/31557600000);
console.log(age)

document.querySelector('.ages').innerHTML = age;
</script>

It will display 0 if they are less than a year old obviously. Try publishing and testing it out on Eino Ratke.

1 Like

Hey mww!

Many thanks! it works perfectly!
Have a good day!