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
Tanya ShahTanya Shah 

How to find date difference

I've written a trigger to update product dates.There are number of products added to particular opportunity and each one has different ServiceDate . So I want to add the difference (service date - Opportunity.closeDate) to each of them so that every product service date is pushed to a new date with difference equal to the number of days between service date and close date. 

Please help !
trigger productUpdate on Opportunity (after update) {
	
	// declare list to hold opportuity line item
	OpportunityLineItem[] olis = [SELECT Id, Name, ServiceDate, Opportunity.CloseDate FROM OpportunityLineItem WHERE OpportunityId IN :Trigger.New];
	for(OpportunityLineItem oli : olis ){
		// perform logic to bumb date somehow...
		//oli.ServiceDate = oli.Opportunity__r.CloseDate + (10);
		Integer dat=oli.ServiceDate.day();
		System.debug('dat prod '+ oli + dat);
		Integer dot=oli.Opportunity.CloseDate.day();
		System.debug('opp cd '+ dot);
		Integer diff=dat-dot;
	//	integer diff = dat.daysBetween(dot);
	    System.debug('diff'+ diff);
        oli.ServiceDate = Trigger.newMap.get(oli.OpportunityId).CloseDate.addDays(diff); 
      
   }
	update olis;

}

 
Shashikant SharmaShashikant Sharma
You could use daysBetween Method of Date Class.
Example: 
Date startDate = Date.newInstance(2008, 1, 1);
Date dueDate = Date.newInstance(2008, 1, 30);
Integer numberDaysDue = startDate.daysBetween(dueDate);
See this :
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_date.htm#apex_System_Date_daysBetween
Tanya ShahTanya Shah
How do i go about implementing with my code..I'm absolutely stucked here . Please help !
AshwaniAshwani
Simply change you line 15 with:

 
oli.ServiceDate = Trigger.newMap.get(oli.OpportunityId).CloseDate.addDays( oli.ServiceDate.daysBetween(oli.Opportunity.CloseDate) );


 
Tanya ShahTanya Shah
This is working but date comes indefinte . I found this link , could you please help me to get a similar one .http://thysmichels.com/2012/04/10/salesforce-update-product-schedule-from-opportunity-product-using-apex-trigger/

In my case i have to update Product Service dates based on Opportunity Close date . Thank you !