How to calculate years between two dates in Apex class in Salesforce?

Sample Code:

Date date1 = System.today();
Date date2 = System.today().addMonths(23);
system.debug('No of months ' + date1.monthsBetween(date2));
String noOfYears = String.valueOf(date1.monthsBetween(date2) / 12) + ' Year(s) ' + String.valueOf(Math.mod(date1.monthsBetween(date2), 12)) + ' Month(s)';
system.debug('No of years ' + noOfYears);

Output:


Cheers!!!

No comments:

Post a Comment