6

I am lost on how to Calculate the difference between two dates (days):

temp_LatestGapLen = temp_PB_CurrSubBeg - temp_PrevSubEnd;

Left variable is defined as Integer, the other two are Dates. Error received is:

Error: Compile Error: Date arithmetic expressions must 
use Integer or Long arguments at line 449 column 53 

Help? I can't find a reliable reference to this online in my searches despite how simple this seems. Is it implying you can only do date vs integer calculations, not date vs date??

Thanks so much.

3 Answers 3

22

Use daysBetween

date startDate = date.newInstance(2008, 1, 1);
date dueDate = date.newInstance(2008, 1, 30);
integer numberDaysDue = startDate.daysBetween(dueDate);

Here ist the doc: Date Methods

0
5

Apex provides a native Date instance method, daysBetween().

date startDate = 
 date.newInstance(2008, 1, 1);
date dueDate = 
 date.newInstance(2008, 1, 30);
integer numberDaysDue = 
 startDate.daysBetween(dueDate);

In your case it would be

temp_LatestGapLen = temp_PB_CurrSubBeg.daysBetween(temp_PrevSubEnd);
0

This is simple approach you can work with. Here is the API doc : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_date.htm

Date startDate = Date.newInstance(2017, 1, 1);
Date dueDate = Date.newInstance(2017, 1, 15);

// No. of days between two dates
Integer numberDaysDue = startDate.daysBetween(dueDate);
System.debug('No. of Days : '+numberDaysDue);

// No. of months between two dates
Integer monthsBetween =  startDate.monthsBetween(dueDate);
System.debug('Months Between : '+monthsBetween);

// No. of hours between two dates
Double noOfhours = (startDate.daysBetween(dueDate)*24*60);
System.debug('No. of hours : '+noOfhours);
1
  • 2
    Hi java, welcome to SFSE. Please take a moment to visit the help center, scroll through the tour, and read How to Answer. Code dumps generally do not make for good answers. Can you edit this post add detail about how this code answers the question, and how it is different than the other answers?
    – Adrian Larson
    Commented Jul 21, 2017 at 19:25

You must log in to answer this question.

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