I am new to salesforce.I am writing a trigger on Case Object. I want to calculate a how much time spent on a case. When Updating, If the status is equal to closed it should save the number of days spent on the case in custom field called 'Number of days spent'. Note: created date is datetime, Closed date is datetime and Number of days spent is Number data type.

1 Answer 1


Instead of doing this via trigger you can have a formula field of type number. Formula would be something like below:

(IF(ISPICKVAL( Status,"Closed"),Datevalue( ClosedDate )-Datevalue(CreatedDate),TODAY()- datevalue(CreatedDate)))

If you want to calculate business days then you can refer the below link:


EDIT: If you are practicing on trigger then in your code get all the case records whose status is getting updated to Closed. Then in a SOQL query retrieve the CaseId , CreatedDate and Closeddate. Save the CaseIds in a set . Then have a FOR loop and inside it create a list of case object. Update the "Number of Days" field there by doing "ClosedDate-Createddate" , and then update all the cases in the list.

Regards! Ruchi

  • I am practising on Triggers buddy
    – Prince
    Commented Sep 15, 2015 at 10:48
  • Updated my answer in Edit.
    – Ruchi
    Commented Sep 15, 2015 at 10:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .