Calculate duration field in Dynamics CRM 2011 via JavaScript and C#

Earlier today while development, I was kinda stuck at one question as to how to calculate duration field value via code based on Actual Start date and End date.

Microsoft Dynamics CRM 2011 actually saves the duration field values in minutes and described below is the technique to calculate the date differences in minutes.

JavaScript

Thanks Athul for this great Script

function DateDiff() {
	var startDate = Xrm.Page.getAttribute('actualstart').getValue();
	var endDate = Xrm.Page.getAttribute('actualend').getValue();

	// to cancel the error when undefined
	if (start == undefined || start == null || end == undefined || end == null) {
		return;
	}

	// Get 1 day
	var day = 1000 * 60 * 60 * 24;

	// Get time in days
	var time = ((end - start) / day) + 1;

	// Can't be less than 0.
	if (time < 0)
		time = 0;
	// Set the duration
	Xrm.Page.getAttribute('actualdurationminutes').setValue(time);
}

C#

// Get attribute values from entity
DateTime startDate = entity.Attributes['actualstart'];
DateTime endDate = entity.Attributes['actualend'];

// Calculate the difference between end and start dates
TimeSpan span = endDate - startDate;

// Assign span to actualduration field
entity.Attributes['actualdurationminutes'] = span.TotalMinutes;

4 Comments Calculate duration field in Dynamics CRM 2011 via JavaScript and C#