Difference Between the Two Dates

As a pega developer, I want to create a function that calculates the difference between two dates in years, months, and days so that I can display the result in the user interface.

Acceptance criteria:

  • The function takes two parameters: the start date and the end date, which are valid date values.
  • The function returns a string that shows the difference between the two dates in the format of “X years, Y months, Z days.”.
  • The function handles edge cases such as leap years, invalid dates, or negative differences.
  • The function is tested with various input values and expected outputs.

Function Code for the above requirement is

  1. Create Library Rule

  2. Create Function with given Code

java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyyMMdd");

Date d1 = null;
Date d2 = null;
String difference = "";
try {
  java.time.LocalDate sDate = java.time.LocalDate.parse(startDate,java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
  java.time.LocalDate eDate = java.time.LocalDate.parse(endDate,java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
  
  java.time.Period period = java.time.Period.between(sDate,eDate);
  
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();

   return + years + " years, " + months + " months, and " + days + " days.";
    
} catch (Exception e) {
	e.printStackTrace();
}
return difference;

@Neeraj_Singh New Improved

java.time.LocalDate sDate = java.time.LocalDate.parse(startDate, java.time.format.DateTimeFormatter.ofPattern("yyyy/MM/dd"));
java.time.LocalDate eDate = java.time.LocalDate.parse(endDate, java.time.format.DateTimeFormatter.ofPattern("yyyy/MM/dd"));

java.time.Period period = java.time.Period.between(sDate, eDate);

int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();

String YearsString = (years > 1) ? "years" : "year";
String monthsString = (months > 1) ? "months" : "month";
String daysString = (days > 1) ? "days" : "day";

return years + " " + YearsString + ", " + months + " " + monthsString + ", and " + days + " " + daysString + ".";

Code

@Neeraj_Singh Can you share the photo of the library rule and function rule that you have implemented for this requirement

Hello @reddyn17278686

Library Name: DateUtils

Imports:

java.time.LocalDate

java.time.format.DateTimeFormatter

java.time.Period

Function Name: calculateDateDifference

Return Type: String



Parameter



Type



Description



startDate



String



The start date in yyyy/MM/dd format



endDate



String



The end date in yyyy/MM/dd format