Help Please with Date to Age Custom Code

Hi, I would really like to be able to convert a CMS Date to an age to display on parent cards using a collection list.

I’ve tried using other people’s custom code but I have no idea how to use it and all the website examples are no longer available, and I haven’t been able to learn from any implementations of this code.

If you could help me with this I’d much appreciate the help. Thank you!

Resources I’ve been trying up to this point:
https://html.form.guide/calculation-forms/age-calculator-html-code-for-website/

Page: Parents

Here is my site Read-Only:
https://preview.webflow.com/preview/spring-pastures-puppies?utm_medium=preview_link&utm_source=designer&utm_content=spring-pastures-puppies&preview=dad8963049ee3c948aac8cceb357f239&pageId=652b6e93222a1e9f8b38f07e&workflow=preview

How exact do you need it to be?

I’ve been considering adding relative time support to SA5’s date formatting library, however the standard underlying libraries calculate the time perceptually.

For example, if a birthday was 547 days ago, it would say “1 year old”, if it’s 548 days ago, it would say “2 years old”. If that’s cool for your purposes, I might add it in as an attribute.

Hi, thanks for replying! so essentially I just need the code to be able to convert a date set in a CMS collection to be converted to an age displayed on a collection list item.


Converting this text block date to say a number that would equal how old it is in years, instead of the date they where born.

date = age (ex: 03/07/2019 = 4)

I just reread your reply, could they be considered 1 after 547 days or 12 months has passed since the date?

No not with momentjs, which is the feature set I’m considering.
You’d just solve that by writing some custom JS.

The reason I’m considering implementing momentjs’s relative times is that it’s a standard and it supports a huge range of formatting and timeframe options. Much more useful as a library feature.

I just thought I’d check in case that met your needs, in which case I might prioritize adding this in.

@memetican - Moment.js is depreciated. Leverage day.js instead. It has feature parity.

Thanks Jeff, I was hoping to leverage Webflow’s internal instance of moment but it appears to be locked tightly within webflow.js.

Dylan try this in place of your current code-

// Calculate the current age in years from birthdate
function calculateAge(birthdate) {
  const now = new Date();
  const diff = now - new Date(birthdate);
  return Math.floor(diff / 31557600000); // 31557600000 ms/year
}

// Find all elements with class 'birthday-date'
const birthdayElements = document.querySelectorAll('.birthday-date');
birthdayElements.forEach(element => {
  const birthdateText = element.textContent;
  const age = calculateAge(birthdateText);
  element.textContent = age.toString();
});

I am using following script to calculate years:

<script>
// Calculate
function diffYears(dateFrom, optDateTo) {
    const from = new Date(dateFrom), to = (optDateTo ? new Date(optDateTo) : new Date()); 
    return to.getFullYear() - from.getFullYear() + Math.min(0, Math.sign(to.getMonth() - from.getMonth() + Math.min(0, Math.sign(to.getDay() - from.getDay()))));
}
// Write
document.write(diffYears('03/07/2019'));
</script>

It covers also leap year. You can either replace the start value in the HTML Embed element or query it from somewhere else (e.g. attributes etc.)

Julian

It Works Great! thanks so much Michael! I had been trying to find a solution via google for the past 3 days to no luck, you are a legend!

I Checked out your website, When I Need help with custom code for more complex projects, I’ll make sure to get in contact.

1 Like

Thanks for sharing your code Julian :slight_smile:

Since I don’t intend to keep the website share link up, here’s an demonstration of how everything works for anyone in the future who also needs to use this code.

Step 1: In your Collection List Item, place a text block called “birthday-date” and connect a cms date field to the text block. (not sure if its important… but make sure the date is “weekday”, “Month” “day”, “year” like in the picture.)

Step 2: Place Michaels Code into the before body tag on what ever page you need this code to work on.

Step 3: Publish! (code will only work on the published website and not the preview)

I’ll add one other approach too, for those who don’t like to mess with code, I’ve added it to SA5’s formatting lib as an attribute. For Dylan’s use case here, you’d;

  • Add the library to your site or page
  • Set your CMS date field format to one of the YYYY-MM-DD style formats, preferably, with or without the time portion
  • Add the custom attribute wfu-format-date, no value needed for this use case
  • Add the custom attribute wfu-format-mode = age

This will render the date as e.g. 4 years.

If you do not want the suffix, you can disable that with wfu-format-suffix = false.

Docs; The lib does advanced date formatting as well as relative time measurements like “8 months ago,” or “in 5 days.”

Demo;