GMASJ

Date Difference in Year

Hi,

Is there a way to get the date different between start and end date in years.

Example : Start Date = 4/1/2020 and End Date = 4/12/2020

Can we get a differnce in year? because I need to use this in a formual

Thanks
GMASJ
Abhishek (Salesforce Developers)
Hi,

you need to know 2 pieces of information:
1. How many full months are between the two dates
2. How many days are leftover from #1

You almost have item #1 - the amount of months, by using:
Integer months = startDate.monthsBetween(endDate);

But that's not entirely accurate, because months between ignores the day - so if you had something on Dec 31st compared to Feb 1st, you'd get 2 months when the reality is 1 month and 1 day. To resolve this, you need to compare the days:
if (startDate.getDate() > endDate.getDate()) {
months--;
}

Now that you have the months, it easy to break that down into years vs months:
Integer years = Math.floor(months / 12.0);
months = months - (years * 12);

Now you're left with just the days. Fortunately, there's also a day between functions you can use!
To do that, let's roll back our end date by the X number of months we've already discovered because we already counted that time as months and years:
Date rolledBackEndDate = endDate.addMonths(0 - months);

And all that's left now is to count the days:
Integer days = startDate.daysBetween(rolledBackEndDate);

For your reference, you can check the below articles,