+ Start a Discussion
Roshan TamrakarRoshan Tamrakar 

Date Subtraction

Hi Experts,

I have a field (first_response__c) of type datetime and I want to find the difference between the value in this field and current date time (system.now()).

Code:
System.debug(first_response__c - system.now()); // first_response__c is greater than system.now() here.

It throws me error like:
"Date/time arithmetic expressions must use Integer and Double arguments"

I also tried to use DATEVALUE() function as found a remedy in other posts, but it does not recognize this method. It returns error like:
"Method does not exist or incorrect signature: DATEVALUE(Datetime)"

I am working in DE org from Eclipse IDE.

What am I doing wrong? Is there any function that differenciates two datetime value and returns me a value in hours?

Thank you,

-Roshan

 

mikefmikef
Roshan:

Please look at the Apex docs under the Datetime Methods and you will find all the methods Apex supports for Datetime fields. here

With that as your starting point I was thinking you could use the method, getTime() this method will return the time in milliseconds of your datetime field. This will be a Long datatype field and you can do a greater or less then comparison.

The error you are getting is because you are trying to use an arithmetic operator on a string datatype, in your debug statement.

Let us know if this helps.


Message Edited by mikef on 05-16-2008 12:25 PM
Roshan TamrakarRoshan Tamrakar

Thanks mikef,

I was just looking for a built-in method in DateTime data type (like DateTime.Diff(DateTime dt)).

Anyway, according to your suggestion, I created my own class as follows:

Code:
public static Long SubtractDate(DateTime highDate, DateTime lowDate){
  Long timeDiff = highDate.getTime() - lowDate.getTime();
  return timeDiff/60000; // 1000 milliseconds * 60 seconds
 }


 
And it worked! This method returns me the difference in hour.

Thanks,
-Roshan