function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
G2WIntegrationG2WIntegration 

How to subtract one DateTime from another

Gotta start first with a rant - the libraries used for DateTIme methods are a piece of crap due to bugs & missing basic functionality.

 

Now that that's out of the way, anyone have ideas on how to get the difference of 2 different DateTime's?  The use case is to ensure that our time stamps are correct so that when we use DateTime1>DateTIme2, it works as expected, which we've manually verified. 

 

Attempt 1: Simple subtraction doesn't work as its not supported

Attempt 2: Convert to double doesn't work as it converts the DateTime to # miliseconds (??) which is more than a 64bit double can handle.  (nevermind that you can't even set milliseconds)

Attempt 3: Convert both to date, use .daysBetween() -too much work as have to basically rebuild the library to handle midnight, new hours, new minutes, etc. 

Best Answer chosen by Admin (Salesforce Developers) 
G2WIntegrationG2WIntegration

Figured out a workaround:

 - Add # days to the DateTime (supported using "+")

 - Use > or < to compare vs. the time frame expected

 

For our example, something like this:

Campaign c=[SELECT g2wLastRegistrantUpdate__c FROM Campaign WHERE Id =<some var>];
DateTime lastUpdate=c.g2wLastRegistrantUpdate__c;
system.assertEquals(null, lastUpdate);
test.StartTest();
  <run method to do stuff and set this field>
test.stopTest();

c=[SELECT g2wLastRegistrantUpdate__c FROM Campaign WHERE Id =:c.Id];

lastUpdate=c.g2wLastRegistrantUpdate__c;
Boolean updateTimeNow=FALSE;
if(DateTime.now()>lastUpdate){
  lastUpdate+=1.0 / (24.0*60.0/10.0);//Add 10min in case the batch was slow
  if(dateTime.now()<lastUpdate)
    updateTimeNow=TRUE;
}
system.assertEquals(TRUE, updateTimeNow);