Question

3
Replies
378
Views
RaviK518 Member since 2016 40 posts
MSoft
Posted: 3 years ago
Last activity: 3 years 4 months ago
Closed
Solved

How to use Java Code inside Declare Expression ?

I am new to Pega , please help me regarding how to achieve this functionality

I have a Date Input Field where User can select his Date Of Birth .

When ever there is a change inside Date Of Birth Field , the Age Property must be calculated Automatically

i want to Write a Declare Expression for this on the Age Property

I have this sample piece of java code , which gives me the age based on Date Of Birth provided

Could you please tell me how can i use this piece of code inside the Declare Expression .

(If this is not the right approach to do , please let me know also )

public class TradeCustomerAgeCalculator {

    public static void main(String[] args) throws Exception {
        String input = "1981-01-01";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar dob = Calendar.getInstance();
        dob.setTime(sdf.parse(input));
        System.out.println("Age is:" + getAge(dob));
    }

    // Returns age given the date of birth
    public static int getAge(Calendar dob) throws Exception {
        Calendar today = Calendar.getInstance();
        int curYear = today.get(Calendar.YEAR);
        int dobYear = dob.get(Calendar.YEAR);
        int age = curYear - dobYear;
        int curMonth = today.get(Calendar.MONTH);
        int dobMonth = dob.get(Calendar.MONTH);
        if (dobMonth > curMonth) { 
            age--;
        } else if (dobMonth == curMonth) { 
            int curDay = today.get(Calendar.DAY_OF_MONTH);
            int dobDay = dob.get(Calendar.DAY_OF_MONTH);
            if (dobDay > curDay) { 
                age--;
            }
        }

        return age;
    }
}

Low-Code App Development
Moderation Team has archived post
Share this page LinkedIn