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!
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.
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.
// 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();
});
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.)
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;