Difference in days between two datetimes

From pmusers
Jump to: navigation, search

The following JavaScript code shows how to calculate the difference in days between to datetime fields.



DynaForm: Difference between dates.json (right click and select Save link as)
Author: Amos Batto (amos@processmaker.com)
Version: 1.0 (2018-07-12)
Tested in: ProcessMaker 3.2.1 Community in Debian 8.4 with PHP 5.6.20 and Firefox 51


Create a Dynaform with two datetime fields whose IDs are "projectStarts" and "projectEnds" and a text field whose ID is "differenceInDays":

formWith2Datetimes.png

Then add the following JavaScript to the DynaForm:

function differenceInDays(startDate, endDate) {
  var oEnd = moment(endDate);
  var oStart = moment(startDate);
  var result = '';
  
  if (oStart.isValid() && oEnd.isValid()) { 
    result = moment.duration(oEnd.diff(oStart)).asDays();
  }
  
  $("#differenceInDays").setValue(result);
}  

$("#projectStarts").setOnchange(function(newVal, oldVal) {
  differenceInDays( newVal, $("#projectEnds").getValue() );
})

$("#projectEnds").setOnchange(function(newVal, oldVal) {
  differenceInDays( $("#projectStarts").getValue(), newVal );
})

When the user enters a value in either of the datetime fields, the change event handler will execute the differenceInDays() function which calculates the difference in days. First, the value of the datatime fields (which is a string in "YYYY-MM-DD HH:MM:SS" format) will be converted to a moment object. Then the .diff() method is used to subtract the difference between the two datetimes and then the .duration() method is used to convert that difference and .asDays() will display it as a whole number of days (either negative or positive).

When a user selects dates in both the "projectStarts" and "projectEnds" fields, then the difference in days is displayed in the text field "differenceInDays":

formInUse.png