Salesforce | Calculate number of years between two dates in apex class

Author - Shalini

Sample Code:

Date date1 = System.today();
Date date2 = System.today().addMonths(30);
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:

No of months === >>>> 30
No of years === >>>> 2

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Salesforce customization, App development or any other software development assistance please contact us at salesforce@webners.com

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Send your message