+ Start a Discussion
Ratheven SivarajahRatheven Sivarajah 

How do you use a date in apex

I am writing a trigger where I am bringing in a Date/Field field from case. It has a letter in it 2023-02-10T16:15:35.000+0000 and when I try to subtract it with "DateTime.now()" I get an error "Date/time expressions must use Integer or Double or Decimal ".

This is my code 
trigger CaseTrigger on Case (before update) {
     for(Case cases: Trigger.new){ 
         if(cases.stopped_time__c != null){
             cases.Total_amount_of_time_in_Hours__c= (DateTime.now()-cases.stopped_time__c );
         } 
    }
}
Best Answer chosen by Ratheven Sivarajah
AISHIK BANERJEE 15AISHIK BANERJEE 15
Hello Ratheven,
                          
cases.Total_amount_of_time_in_Hours__c= (DateTime.now().getTime()-cases.ClosedDate.getTime() )/(1000.0 * 60.0 * 60.0);

In this code, we use the getTime method to convert the DateTime objects to the number of milliseconds, and then divide that number by the number of milliseconds in an hour to get the total number of hours.

I hope this will help.
Thanks

All Answers

Abdul KhatriAbdul Khatri
Hi Ratheven,

I hope the following article will help you how to move forward, referencing the issue you are getting
https://www.xgeek.net/salesforce/calculate-the-difference-between-two-datetimes-in-salesforce/

For More about DateTime Date functionality in Salesforce here is a trailhead
https://trailhead.salesforce.com/content/learn/modules/advanced_formulas/date_formulas

I hope this will help
AISHIK BANERJEE 15AISHIK BANERJEE 15
Hello Ratheven,
                          
cases.Total_amount_of_time_in_Hours__c= (DateTime.now().getTime()-cases.ClosedDate.getTime() )/(1000.0 * 60.0 * 60.0);

In this code, we use the getTime method to convert the DateTime objects to the number of milliseconds, and then divide that number by the number of milliseconds in an hour to get the total number of hours.

I hope this will help.
Thanks
This was selected as the best answer
kiwis brownkiwis brown
yes this is very helpful for me.
filmplus app (http://filmplusapk.info/)