How can I calculate age from a datafield “date” of my collection? It’s possible to be a new colunm inside the colection or just a presentation for the datafield “date”?
A couple issues need to be dealt with…
You can add an “age” column to your collection which be used for the calculated age. Connect it to the table to display the age. Use the afterGet() hook ( go here for more information ) to calculate the age so it will be displayed in the table.
Here’s a sample snippet adapted from the sample in the hooks documentation:
export function myCollection_afterGet(item, context) {
let hookContext = context;
// calculate age from the birthday field in the collection
item.age = < calculate age from item.birthday >;
return item;
}
You can then use the following code in the above hook, to calculate the age something like this:
var bdate = new Date(item.date);
var birth_year = bdate.getFullYear();
console.log(birth_year);
var birth_month = bdate.getMonth();
console.log(birth_month);
var birth_day = bdate.getDate();
console.log(birth_day);
var today_date = new Date();
var today_year = today_date.getFullYear();
var today_month = today_date.getMonth();
var today_day = today_date.getDate();
var age = today_year - birth_year;
if ( today_month < (birth_month - 1))
{
age--;
}
if (((birth_month - 1) == today_month) && (today_day < birth_day))
{
age--;
}
console.log(age);
Note: console.log() is your friend. I use it generously to help me see what’s going on with my code.
Hopefully these code snippets can get you going the right direction.
Have fun,
Yisrael
Thank you Yisrael. I will try.