Skip to main content
ar54298644
Participant
January 7, 2019
Question

Time Difference Calculation with an Exception

  • January 7, 2019
  • 2 replies
  • 389 views

I am working on a vacation request form that has a field for start time and end time in h:mm tt format.  I have a script that is working for calculating the difference in those fields, however, I need this have an exception and I am not sure what to add/change.

If an employee request 8:00 am to 12:00 pm the script works fine, however, if they request 8:00 am to 5:00 pm it fails because it doesn't take the hour lunch period into consideration.

Please advise.

// get the values of the fields

var sStart = this.getField("Start TimeRow1").value;

var sEnd = this.getField("End TimeRow1").value;

// clear field as a default action

event.value = "";

// compute only if we have values

if(sStart != "" && sEnd != "") {

// add a formatted date value to the time field values

sStart = "1-Jan-1970 " + sStart;

sEnd = "1-Jan-1970 " + sEnd;

// convert the date time strings to date object

var oStart = util.scand("d-mmm-yyyy h:MM tt", sStart);

var oEnd = util.scand("d-mmm-yyyy h:MM tt", sEnd);

// convert date object to milliseconds since 1-Jan-1970

var nStart = oStart.getTime();

var nEnd = oEnd.getTime();

// compute the difference in milliseconds

var nDiff = nEnd - nStart;

// convert to seconds

var nSeconds = Math.floor(nDiff / 1000);

// compute the whole hours from the minutes

var nHrs = Math.floor(nSeconds / (60 * 60));

// compute the remaining minutes

var nMins = (nSeconds / 60) % 60;

// set field value string to formatted time string

event.value = nHrs + ":" + util.printf("%,202.0f", nMins);

} // end have values

This topic has been closed for replies.

2 replies

Inspiring
January 7, 2019

This is what can happen when one simply copies and pastes code without any understanding of code or the function of the code. If this were computing the time of an airplane, bus, or train trip the calculation would be correct for the involved time interval for the trip.

What was the context of the original post?

Seems like that how it the time interval works in the real world, unless one adds a field for the time taken for lunch or the start and end times of the lunch break.

How do you want to proceed?

try67
Community Expert
Community Expert
January 7, 2019

What's the logic behind it? If it's more than X hours reduce one hour? If it includes 12:00-1:00 reduce one hour? etc.

ar54298644
Participant
January 7, 2019

Yes, the logic would be if the total exceeds 4 hours then deduct 1 hour.

try67
Community Expert
Community Expert
January 7, 2019

OK, then after this line of the code:

var nSeconds = Math.floor(nDiff / 1000);

Add this:

if (nSeconds>14400) nSeconds-=3600;