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
DJP1SDJP1S 

Get Hours Difference between two Datetime fields

I've got this little bit of coe: 

if(ac.Start_Time__c != null && ac.End_Time__c != null){
            	decimal Hours = decimal.valueOf((ac.End_Time__c.getTime() -  ac.Start_Time__c.getTime())/(1000*60*60));
                system.debug('$$$ Hours:' + Hours);
               	ac.Hours__c = Hours;
            }

 

And it returns a decimal just fine if I have the Start_Time__c and End_Time__c as a whole hour (e.g., 6:00 pm), but if I have I have a partial hour (Start Time at 2 pm and End Time at 6:30pm), I get 4.00 returned instead of 4.5. Why is this?

Best Answer chosen by Admin (Salesforce Developers) 
@anilbathula@@anilbathula@

Hi 

 

I tried this and dont know why it is not returning 4.5 .

But i did a workaround and i got it correct.

decimal Hours = decimal.valueof((a.endtime__c.getTime() - a.starttime__c.getTime())/(60*60));
decimal s=(hours/1000);
system.debug('a::->'+hours);
system.debug('b::->'+s);

 

Thanks

Anil.B

All Answers

@anilbathula@@anilbathula@

Hi 

 

I tried this and dont know why it is not returning 4.5 .

But i did a workaround and i got it correct.

decimal Hours = decimal.valueof((a.endtime__c.getTime() - a.starttime__c.getTime())/(60*60));
decimal s=(hours/1000);
system.debug('a::->'+hours);
system.debug('b::->'+s);

 

Thanks

Anil.B

This was selected as the best answer
DJP1SDJP1S

Here's what I ended up doing - something similar to what you've got (finishing the arithmetic in another variable declaration).

 

            if(ac.Start_Time__c != null && ac.End_Time__c != null){
            	decimal Hours = decimal.valueOf((ac.End_Time__c.getTime() - ac.Start_Time__c.getTime()));
                decimal hoursnew = Hours/(1000*60*60);
                system.debug('$$$ Hours:' + Hours);
                system.debug('$$$ Hoursnew:' + hoursnew);
               	ac.Hours__c = hoursnew;
            }

 

 

Yours should work as well. Thanks!