I am using DataTables to collect duration spent fundraising for each person and then display their share of the funds raised to go towards a camp.
I am trying to add duration together using moment (the duration can be greater than 24 hours). I then want to get the fraction for each and times by the dollar amount raised to work out the amount to disperse to each person. For instance total calculated duration spent is 10 hours and total raised is $100.00, James spent 2:30 which is 0.25 of 10 hours so will receive $25.00 towards the camp.
My calculation of total hours only returns the last duration entered (e.g, if I enter 1:30 and 3:00 then totalHours returned is 3:00).
How do I correctly add the duration? How do I divide each duration into totalHours to get the correct fraction? How do I then write the calculated disbursement to column 7 for each person?
My code is:
var totalHours;
// this gets each node (cell) in the final column:
memDispTable.columns(5).nodes().to$()[0].forEach(function (item) {
// see if the display value is a number (i.e. not blank):
var hours = $('input', item ).val();
console.log("hours: " + hours);
if (moment(hours, "HH:mm").isValid()) {
totalHours = moment.duration(moment.utc(totalHours,'HH:mm')).add(moment.duration(hours, 'HH:mm'));
totalHours = moment.utc(totalHours.as('milliseconds')).format("HH:mm");
console.log("totalHours: " + totalHours);
}
});
$('#showDispHours').val(totalHours);
@AlwaysHelping provided this solution, except it does not go past 24 hours:
var totalHours = 0;
// this gets each node (cell) in the final column:
memDispTable.columns(5).nodes().to$()[0].forEach(function (item) {
// see if the display value is a number (i.e. not blank):
var hours = $('input', item ).val();
console.log("hours: " + hours);
if (moment(hours, "HH:mm").isValid()) {
var start = moment(hours, "HH:mm");
var diff = start.diff(start.clone().startOf('day'));
totalHours += diff;
console.log("totalHours: " + totalHours);
}
});
var duration = moment.duration(totalHours); //get total
$("#showDispHours").text(duration.hours() + ':' + duration.minutes());
In addition to the excellent answer provided by @AlwaydHelping the final piece is from:
How to convert time milliseconds to hours, min, sec format in JavaScript?
seconds = Math.floor((totalHours / 1000) % 60),
minutes = Math.floor((totalHours / (1000 * 60)) % 60),
hours = Math.floor((totalHours / (1000 * 60 * 60)));
$("#showDispHours").text(hours + ':' + minutes);