Images

Calculating Time Spent (in minutes) on an activity via Javascript in MS CRM 2015

Hello Readers,

its been so many days, I was waiting to write something very commonly required yet useful feature.

I have been asked so many times by my customers, How can i see the time spent on an activity, if we have entered the ‘Start Time’ & ‘Finish Time’. Yes, we can, its easy and simple. This time calculation can also be used for calculating, how much total we spent on a case resolution if we replace ‘Start Time’ by ‘Created on’ & ‘Finish Time’ by ;Actual Resolution on’ ; so on and so forth there can be multiple usage of this javascript based on your time calculation requirements. In this scenario, i am taking up a custom activity called ‘Repair Activity’; following is a screenshot:

b2

 

Please note that the time spent field is a Deciaml Field

We need to follow the following steps:

Step 1: write the Javascript code as shown below-

function time()
{
var stdate=Xrm.Page.getAttribute(“new_starttime”).getValue();
var endate=Xrm.Page.getAttribute(“new_finishtime”).getValue();

if(stdate==null && endate==null)
{
alert(“Please enter the Start Time / Finish Time…”);
return false;
}
if(stdate==null)
{
alert(“Please enter the Start Time !”);
return false;
}
if(endate==null)
{
alert(“Please enter the Finish Time !”);
return false;
}

var st=stdate.getTime();
var ed=endate.getTime();
var sdiff=(ed-st);
var h=(sdiff/60/1000);
var p=parseInt(h);
var tm=p.toString();
Xrm.Page.getAttribute(“new_timespent”).setValue(tm);
}

Step 2: Add a webresource in CRM

Add a new webresource by typing in a name, Display Name, Language & Type>>Save & Publish>>URL will be genrated

b6

 

Step 3: Add this webresource to form Libraries

Go to ‘Repair Activity’ Form Editor>> Form Properties>>Form Libraries>>Add

b5

And also manage the ‘Event Handler’ by setting the event when you want this Javascript to be executed, so, i will set it on ‘On Save’ & set control to ‘Form’ & click OK

b7

Once done save the form & publish it

Result : That’s it, here you go,now we can see the time spent as soon as we save the form; this javascript also, gives us an alert if we have not provided any value in Start & Finish time

b8

b9

Happy CRMing !!