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.
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.