Friday, September 2, 2016

Calculate time stamps in CRM 2015

Part of the functionality I'm trying to establish, is to calculate
the difference between the two fields and set it as value of another field (new_timeStampCalc).

For example: start time stamp records 14:45 and stop time stamp records 14:57.
new_timeStampCalc will be 0:12.


Three fields needed on the form:
  1. new_starttimestamp (Date/time)
  2. new_stoptimestamp (Date/Time)
  3. new_timestampcalc (text)
User opens the record and clicks on start button which in turn will set the value of "new_starttimestamp" field. User closes the record. Sometime in the future, user opens the record again and clicks on Stop button which calls the "SetEndTimeStamp" function which sets the "new_stoptimestamp" field and the "new_timestampcalc" field using DateDiff function.
Here is the adjusted script. You may need to play around with the DateDiff function:
function formOnload() {
   window.parent.setTimeStamp = setTimeStamp;
   window.parent.setEndTimeStamp = setEndTimeStamp;
}

function setTimeStamp() {
   var d = new Date();
   if(Xrm.Page.getAttribute("new_starttimestamp") != null){
       Xrm.Page.getAttribute("new_starttimestamp").setValue(d);
   }
}

// Called from the stop button
function setEndTimeStamp() {
   var endTime = new Date();
   
   if(Xrm.Page.getAttribute("new_stoptimestamp") != null){
       Xrm.Page.getAttribute("new_stoptimestamp").setValue(endTime);
   }
    var startTime = Xrm.Page.getAttribute("new_starttimestamp").getValue();
 Xrm.Page.getAttribute("new_timestampcalc").setValue(DateDiff(endTime, startTime));
}

/*
var d1 = new Date("2015-07-25T12:05:30");
var d2 = new Date();
console.log(DateDiff(d2, d1));
*/
function DateDiff(d2, d1) {
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
var months = 0;
var years = 0;
var subtract = 0;

if(d2.getSeconds() < d1.getSeconds()) {
seconds = (d2.getSeconds() + 60) - d1.getSeconds();
subtract = 1;
} else {
seconds = d2.getSeconds() - d1.getSeconds();
}

if(d2.getMinutes() < d1.getMinutes()) {
minutes = (d2.getMinutes() + 60 - subtract) - d1.getMinutes();
subtract = 1;
} else {
minutes = (d2.getMinutes() - subtract) - d1.getMinutes();
subtract = 0;
}

if(d2.getHours() < d1.getHours()) {
hours = (d2.getHours() + 24 - subtract) - d1.getHours();
subtract = 1;
} else {
hours = (d2.getHours() - subtract) - d1.getHours();
subtract = 0;
}

if(d2.getDate() < d1.getDate()) {
days = (d2.getDate() + 30 - subtract) - d1.getDate();
subtract = 1;
} else {
days = (d2.getDate() - subtract) - d1.getDate();
subtract = 0;
}

if(d2.getMonth() < d1.getMonth()) {
months = (d2.getMonth() + 12 - subtract) - d1.getMonth();
subtract = 1;
} else {
months = (d2.getMonth() - subtract) - d1.getMonth();
subtract = 0;
}

years = (d2.getFullYear() - subtract) - d1.getFullYear();

return years + ":" + months + ":" + days + ":" + hours + ":" + minutes + ":" + seconds;
}

Reference -  https://community.dynamics.com/crm/f/117/t/210360