Form Math Equation

Hello ladies and gents,

I have a form with a section of three inputs, one for start time, the second for end time and the third for duration. I currently have it set up where the user enters the start and end time, and the duration is automatically filled into the duration field (end time - start time). My issue is, it is displaying the result as a decimal (i.e., “1.35”). How do I get it to display the duration in the HH:MM format for 24-hour clock (i.e., “01:35”)?

I also have the same setup for calculating the start and end mileage, how do I make that one so that it accepts comma’s between the number? Such as “12,345 - 12, 445 = 100” and if possible, can letters be entered without affecting the equation? Such as, “12,345 km - 12,445 km = 100 km”?

As usual and assistance would be greatly appreciated!!

Below is my code:

$(function () {
function calculate() {
var time1 = $(".onsite_time").val().split(’:’), time2 = $(".offsite_time").val().split(’:’);
var hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
var hours = hours2 - hours1, mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
}
else {
mins = (mins2 + 60) - mins1;
hours–;
}
mins = mins / 60; // take percentage in 60
hours += mins;
hours = hours.toFixed(2);
$(".duration").val(hours);
}
$(".onsite_time,.offsite_time").change(calculate);
calculate();
});

Well, you can format the results using this code:

var hours = new Date();
hours.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});

This sets the hours variable to a “Date” format. Then, it alters it to display just hour and minutes.
You do a lot of work to get the minutes. You can just use “Date” functions to do it with ease! Like:

var diff =(time1.getTime() - time2.getTime()) / 1000;
  diff /= 60;
  results = Math.abs(Math.round(diff));

Not tested. The getTime() turns the incoming value into milliseconds. Subtract the two, turn into seconds and divide by 60 for minutes. Much less work!

Thank you for your response! I’m not experienced with JavaScript and new to all of this, where would I add these two codes into the script I have and what would I remove?

Is your calculation function which is called somewhere else in your page. Put the code into it and replace all of the rest of that part. Something, untested, like this should do it:

function calculate() {
  var diff =(time1.getTime() - time2.getTime()) / 1000;
  diff /= 60;
  $(".duration").val(Math.abs(Math.round(diff)));
}

Again, not tested but should work for you. Let us know…

Sponsor our Newsletter | Privacy Policy | Terms of Service