## Thursday, November 25, 2010

### Age this month calculation in Crystal Reports

I keep having lots of fun developing enterprise reports with the excellent Crystal Reports.

Today I needed to calculate the age of a person for this month. The typical use of this formula would be something like “determine if an employee is turning 65 years old this month).

I was able to come with the following Crystal Formula Syntax:

`// Age this month calculation WhileReadingRecords;dateTimeVar _1stOftheMonth := CurrentDate; dateTimeVar LastOftheMonth := CurrentDate; // Get the run date and make it the 1st day of the current month_1stOftheMonth := Date(Year(_1stOftheMonth), Month(_1stOftheMonth), 01);// Get the next month's 1 st day. Subtract 1 day to get the last day of the current monthLastOftheMonth := DateAdd( "d", -1, DateAdd("m", 1, _1stOftheMonth) );// Proceed with the age calculation taking into consideration the leap yearif (Month(LastOftheMonth) * 100) + Day(LastOftheMonth) >=   (Month(CDate({Employee_Master.BirthDate})) * 100) + Day(CDate({Employee_Master.BirthDate}))  then     Year (LastOftheMonth) - Year(CDate({Employee_Master.BirthDate}))  else     Year (LastOftheMonth) - Year(CDate({Employee_Master.BirthDate})) - 1;`

An interesting nuance about this formula: if one substitutes the CurrentDate (on line 3 and 4)  to an event date of interest (being a certain date or a database field) it is possible to calculate the age on this specific date!