Calculating a current age string

I saw some previous posts but couldn’t figure out a method that works. “I have $DOB as a Date attribute and $ClientAge as a String. I want to calculate and display age as ‘9 yrs 4 mos’. What’s the correct action code?” Many thanks!

  function age(bday:date) {                                                                                                                 
      var:date today = date("today");                                                                                                            
      var:number totalMonths = (today.year - bday.year) * 12 + (today.month - bday.month);                                                         
      if (today.day < bday.day) { totalMonths = totalMonths - 1; }                                                                          
      var:number ageYears = floor(totalMonths / 12);
      var:number ageMonths = totalMonths - ageYears * 12;
      return ageYears + " years " + ageMonths + " months";
  }

Claude Code did almost all the work here. It is a bit uneasy about saying “6 years 0 months”, as this does, or “0 years 4 months” for that matter. Those can be fixed easily, but this keeps things simpler.

Thanks so much. I’ll look up how to enter this function so it appears document wide.

Assumption: partial months are rounded down. 5 years 6 months is any duration between 6 months and zero days and 1 day less than 7 months.

Try this TBX: Age-maths-1.tbx (114.8 KB)

Open the TBX, select the 3 text notes and then use the Stamps menu to apply the ‘Get Age’. Then inspect the $Text of each note and check the result.

In each test note the Date of Birth is stored in $StartDate and which is set as a Displayed Attribute.

how about:
$MyAge = floor(days(date($MyDOB), date(“today”)) / 365.25);

and with formatting:
var totalDays = days(date($MyDOB), date(“today”));
var yrs = floor(totalDays / 365.25);
var mos = floor((totalDays % 365.25) / 30.44);
$MyAge = yrs + " yrs" + (mos > 0 ? " " + mos + " mos" : “”);

1 Like