Calculate age

Hi everyone,
the user gives me his date of birth, and I would need to calculate his age. I tried to write the code below, but it doesn’t seem to work … Could you please give me some suggestions?

Thanks in advance as always.


$w(“#DTS2”).onReady( function () { . // the dbms where the birthday is saved
var today = new Date(); // today date
var birthday = $w(“#DTS2”).getCurrentItem().Birthday; // the field of the dbms with the birthday
let age = today.getFullYear() - birthday.getFullYear(); // only the year of today - only the birthday
$w(“#age”).text === age; // show the age in a field
});

Just use the search function in this forum and you will find many old posts about this.
https://www.wix.com/corvid/forum/community-discussion/calculate-age-from-date-from-collection
https://www.wix.com/corvid/forum/community-discussion/displaying-accurate-age-based-on-dob-stored-in-collection
https://www.wix.com/corvid/forum/community-discussion/calculate-age-from-date
https://www.wix.com/corvid/forum/community-discussion/automatic-age-field-in-the-database

Hi, #GOS
I had already seen all the links suggested by you, in fact my code is the result of two of those proposed, but I don’t understand why it doesn’t work.

Can you help me, please ?

For a start do you have that trailing period on line one in your code? Is it a syntax error?

Though this code needs work because it doesn’t consider whether a birthday has occurred this year or not - you’re going to have lots of off-by-one errors.

Hi Lee
what do you mean? the compiler doesn’t give me any errors, simply the code doesn’t work. can you help me? it’s almost a month and I still haven’t been able to find an alternative.

This still isn’t perfect and might still get it wrong on birthdays etc. but will produce much more accurate results than what you started with.

$w.onReady(() =>
{
	$w('#dataset1').onReady(() =>
	{
		const record = $w('#dataset1').getCurrentItem();
		const now = new Date().getTime();
		const age = Math.floor((now - record.dob) / 1000 / 60 / 60 / 24 / 365.25);
		$w('#age').text = age.toString();
	});
});

If you wanted it to be perfect you’d probably be best off using a time library like moment.js (Wix offers this in their Node package manager). GOS’s first link also contains a potentially more accurate calculation method under calculation.js.

If you look at line one of your code you have a period between the code and the comment. If that’s present in your code (and wasn’t added when copy and pasting) it is a syntax error.

Nice - as always, thanks Lee!!