-
How to calculate someone’s age based on the current date vs a string of date
So I’m having trouble figuring out this expression. 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 string will be inserted and on the other layer, the age should be outputted.
So what I have now is this:
var birthDateString = thisComp.layer("Birth Date");
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!
TIA! 🙂