Search code examples
salesforceapex-codeapex

datedifference in days in a datetime field in apex


How can i find the difference of 2 datetime fields in days ?

I couldnt find anything on the documentation for this. i can see that there are methods to add hours, days but cant find anything on getting the datedifference.

The one way i can think of is to convert both fields into datetime using valueof and use the date function daysbetween.

    integer Days__c = Date.today().daysBetween(date.valueof(datetimefield__c));

Any are there any other better options?


Solution

  • You could do this:

    integer Days = Integer.valueOf((Date2.getTime() - Date1.getTime())/(1000*60*60*24));
    

    This would convert each date into milliseconds, subtract one from the other, then convert it into integer of days. or could convert into decimal days.