So I need to to calculate someone’s age based on the current date vs a string of date. I’m having trouble figuring out the expression to calculate the age.
I have to calculate someone’s age from a string that is the birth date, e.g 12/22/1989 based on the current date.
On one text layer, the birthdate(e.g 12/22/1989) will be inputted and on the other layer, the age should be outputted.
TIA!
So what I have now is this:
var birthDateString = thisComp.layer("Birth Date").text.sourceText;
function dateToCurrentFormat(dateString) {
var parts = dateString.split(/[/]/);
var month = Number(parts[0]) - 1; // months are 0-based
var day = Number(parts[1]);
var year = Number(parts[2]);
return new Date(year, month, day);
}
function difference(date1, date2, interval) {
var second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24,
week = day * 7;
date1 = new Date(date1);
date2 = new Date(date2);
var timediff = date2 - date1;
if (isNaN(timediff)) return NaN;
switch (interval) {
case "years":
return date2.getFullYear() - date1.getFullYear();
case "months":
return (
(date2.getFullYear() * 12 + date2.getMonth()) -
(date1.getFullYear() * 12 + date1.getMonth())
);
case "weeks":
return Math.floor(timediff / week);
case "days":
return Math.floor(timediff / day);
case "hours":
return Math.floor(timediff / hour);
case "minutes":
return Math.floor(timediff / minute);
case "seconds":
return Math.floor(timediff / second);
default:
return undefined;
}
}
var birthDate = dateToCurrentFormat(birthDateString);
var age = difference(birthDate, new Date(), "years");
var ageString = age + " years old";
ageString;
Each time I’m getting an error for different things. First, it was “dateToCurrentFormat is not defined” then, ” difference is not defined” and then “object of type found where a Number, Array, or property is needed” for the variable age.
What am I doing wrong here? Maybe I’m doing it more difficult than it should be, if there’s an easier way to get to the result please let me know!
I've also tried the following:
var dob = thisComp.layer("Birth Date").text.sourceText;
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
age;
But I'm getting the result NaN. I'm guessing I need to do something with parse or integer in this code? But not sure how to go about it.