News

Tweets













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 month
LastOftheMonth := DateAdd( "d", -1, DateAdd("m", 1, _1stOftheMonth) );
 
// Proceed with the age calculation taking into consideration the leap year
if (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!

Thursday, November 25, 2010 10:03 AM

Feedback

# Crystal Reports

I liked it.
thank you for your great posting 12/1/2010 5:44 AM | driver6

Post A Comment
Title:
Name:
Email:
Comment:
Verification: