I figured that I can retrieve the number of the passed years since a Date field by usin formula, but what if I want to do this in apex class.

I have a date field that I want to calculate the number of years from, and return it as integer.

1 Answer 1


Here's an apex code that solved the problem

Date production_d = product.Date__c;
Date current_date = date.today();

Decimal years = (production_d.daysBetween(current_date ))/365.25; // days to years
return years.round(System.RoundingMode.DOWN); // return Integer
  • 1
    Except, it's not 365.25. It's closer to 365.242, and changes every year. The difference would make a difference for dates very far apart. A better idea would be to calculate the day as a literal number (366*year+31*(0-based month)+(0-based day). Subtract the two values, then divide by 366, and you're good.
    – sfdcfox
    Commented Sep 21, 2014 at 14:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .