Reply
Regular Contributor
G2WIntegration
Posts: 29
0
Accepted Solution

How to subtract one DateTime from another

[ Edited ]

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. 

Regular Contributor
G2WIntegration
Posts: 29
0

Re: How to subtract one DateTime from another

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);