Skip to main content
Participant
January 3, 2019
Question

Calculate Difference in hours between Start and End Date/Times in mm/dd/yy h:MM tt format

  • January 3, 2019
  • 1 reply
  • 855 views

I am creating a fillable form for our employees to request vacation time off.  I have pieced together calculations scripts from various forums but can not get the result I want. Say an employee wants to take 01/04/19 off.  They would enter a start date/time of 01/04/19 8:00 am and end date/time of 01/04/19 5:00 pm.  I want the form to calculate the difference in hours.  Now the trick is that if they take more than 4 hours (leave after 12 noon) the deduction needs to deduct an hour from the result, to account for the lunch hour so that employee is only charged 8 hours of vacation rather than 9.  Here is the script I have pieced together, please advise:

function Date2Num(cFormat, cString) {

// convert cString with cFormat to number of minutes from Epoch date

// convert to date time object

var oDate = util.scand(cFormat, cString);

// convert date time object to minutes

return Math.floor(oDate.getTime() / (1000 * 60));

} // end Date2Num function

// format for input date & time

var cDateFormat = "mm/dd/yy h:MM tt";

// field names

var cStartField = "Start DateTimeRow1";

var cEndField = "End DateTimeRow1";

// get field values

var cStart = this.getField(cStartField).value;

var cEnd = this.getField(cEndField).value;

// clear the result value

event.value = "";

// compute the difference in minutes if there is data

  if(cStart !== "" && cEnd !== "") {

if (cEnd > 12) {

nDiff = (Date2Num(cDateFormat, cEnd)-60) -  Date2Num(cDateFormat, cStart);

} else {

nDiff = Date2Num(cDateFormat, cEnd) -  Date2Num(cDateFormat, cStart);

}

}

// convert to hours

event.value = nDiff / 60;

This topic has been closed for replies.

1 reply

try67
Community Expert
Community Expert
January 3, 2019

There are errors in your code. You never define the nDiff variable. Once I do that the result is 9, as expected.

Participant
January 3, 2019

Thank you can you please tell me what should be used rather in nDiff?  I don't know javascript and like I said before I pieced this together from various other forum posts.

try67
Community Expert
Community Expert
January 3, 2019

After this line:

event.value = "";

Add this:

var nDiff = 0;