# Calculate the difference between two dates in salesforce

public class trigger36 {
public static void trigger1(List<Account> accList)
{
Set<id> accId = new Set<id>();
List<Account> Listoppos = new List<Account>();
Map<id,List<Opportunity>> MapacOp = new Map<id,List<Opportunity>>();
List<Opportunity> updated = new List<Opportunity>();

for(Account a : accList)
{
accId.add(a.id);// fetch id of all accounts which were updated
}

Listoppos =  [select Id, (Select name,StageName,CreatedDate from Opportunities) from Account where ID IN: accId];
for(Account a :Listoppos)
{
MapacOp.put(a.id, a.opportunities);
}

for(Id i: accId)
{
List<Opportunity> x = MapacOp.get(i);
for(opportunity xx:x)
{
if(xx.StageName != 'ClosedWon' &&  System.Today() -  30 > xx.CreatedDate.date())
{
xx.StageName ='Closed Lost';
updated.add(xx);
}
}
if(updated.size() > 0)
{
update updated;
}
}
}
}

I am trying to write a trigger which changes the opportunity StageName as per the conditions: Update all Opportunities Stage to close lost if an opportunity created date is greater than 30 days from today and stage not equal to close won.

My code seems to be working fine but I wish to understand why System.Today() - 30 > xx.CreatedDate.date() seems to be working fine but System.Today() - xx.CreatedDate.date() > 30 seems to fire an error,

Date expressions must use Integer or Long

What exactly is this error trying to imply?

PS. xx is an Opportunity object and x is list<Opportunity>.

## 1 Answer

It's simply saying you can't add/subtract two dates. The - and + operators are overloaded on Date to call the addDays function with the Integer/Long as the parameter, and returns a date that results from that method.

If you really wanted the time between two dates, you'd have to convert them to DateTime values, then use the getTime method to count the number of milliseconds between the two, and finally divide by 86400000 to get the number of days.

So, logistically speaking, it's much easier to use addDays to adjust one of the dates, and then compare the resulting value. Alternatively, you can use the daysBetween method if you wanted that comparison to read a bit clearer:

if(xx.CreatedDate.date().daysBetween(Date.Today()) > 30) {
• Thanks for the answer @sfdcfox, clear and crisp. I assumed apex would allow use of +,- on dates just like formulas do. Commented Nov 5, 2022 at 21:43
• @codedeveloper That's not an unfair assumption, especially if you start from formulas then move to Apex. I came from the other direction (Java, ScriptScript, etc), so I wasn't entirely surprised it didn't support it. That actually would be a pretty nifty Idea that I could get behind.
– sfdcfox
Commented Nov 5, 2022 at 21:51
• Thanks again for the clarification. :) Commented Nov 6, 2022 at 14:04