Thursday, November 7, 2019

Calculate number of years between two dates in salesforce using apex

Sample Code
Date dtToday = Date.today();
Date dtOther = Date.today().addMonths(50);
system.debug('Number of months  ===> ' + dtToday.monthsBetween(dtOther));
String strNoOfYears = String.valueOf(dtToday.monthsBetween(dtOther) / 12) + ' Year(s) ' + String.valueOf(Math.mod(dtToday.monthsBetween(dtOther), 12)) + ' Month(s)';
system.debug('Difference b/w two dates ====>  ' + strNoOfYears);

Result

No comments:

Post a Comment