As sfdcfox points out in his comment, you seem to be mixing syntax for formulas and syntax for Apex. I get the impression that you found a formula somewhere and are trying to convert it to Apex (you have variables! USE THEM!). The rest of this answer is framed around the assumption that you're doing this in Apex.
The error itself is because <Datetime> - <Datetime>
is not valid in Apex. It is valid in formulas and gives you a result like 2.123
(where 2 is the number of days and .123
is a fractional day down to a precision of seconds), but not in Apex.
So everywhere you have (DateTime.Now() - SavedTime__c)
is a syntax error.
Like the error message is telling you, you can only use an Integer, Double, or Decimal when you want to add/subtract from a Datetime. So Datetime.now() - 2
, for example, would subtract 2 days.
The Datetime class itself doesn't have any methods that we can use to get a decimal representation of the difference between them. Seems like an odd omission by Salesforce, given that we have daysBetween()
on Date
, but it doesn't look like Java has a single method to accomplish the same thing either (and I'm less and less surprised by Salesforce's inconsistencies as time goes on).
Anyway, to do this in Apex, you'll need to work with timestamps (number of seconds/milliseconds between the unix epoch of 1970-01-01T00:00:00Z
and a given Datetime
). The getTime()
method gets you that information.
// Difference in # of milliseconds
Long difference = Datetime.now().getTime() - SavedTime__c.getTime();
// There are 1000 milliseconds in a second
// 60 seconds in a minute
// and 60 minutes in an hour
// 1000 * 60 * 60 = 3,600,000
// Division between two Longs will remove the fractional part (i.e. it'll
// automatically floor the result)
Long hourDifference = difference / 3600000;
// If you want fractional hours, make either the numerator or denominator a Decimal
//Decimal hourDifference = difference / 3600000.0;
The logic you have to decide between putting the hour difference or 0 into the final field is nonsensical. If the number of days between two datetimes is at least 2, then the number of hours will always be positive. The else block where you have CalculatedHours__c = 0;
is unreachable.
Thus, with your current logic, you should simply assign the difference in hours to CalculatedHours__c
if that difference is at least 2 days (i.e. 48 hours). You haven't provided enough detail for us to know what should happen when the difference is less than 48 hours.