OneLazy OneLazy - 4 years ago 106
Javascript Question

How to Compute time via DataTable footer

I need to compute time in DataTable footer but all I have is this

"footerCallback": function(row, data, start, end, display) {
var api = this.api(),
data;
var intVal = function(i) {
return typeof i === 'string' ? i.replace(/[\$,]/g, '') * 1 : typeof i === 'number' ? i : 0;
};

totalhrs = api.column(3).data().reduce(function(a, b) {
return intVal(a) + intVal(b);
}, 0);
totalhrs_page = api.column(3, {
page: 'current'
}).data().reduce(function(a, b) {
return intVal(a) + intVal(b);
}, 0);
// Update footer
$('#totalHours').html("<b>" + "TOTAL Hours: " + totalhrs_page + "/" + totalhrs + "</b>");
}


As you can see in the demo, I'm getting the SUM of all the rows in the Hours Spent Column, what I need is to compute it for time. When the decimal place became >= 60 then it should +1 the whole number. Say the result is 23.82, it should be 24.22. Right now it only +1 the whole number when the decimal place reaches a hundred.

Is there an easier way to do this ?

Thanks!

Answer Source

You can convert it to minutes in reduce function

  totalhrs = api.column(3).data().reduce(function(a, b) {
        b = b.split(".");
        var hours = b[0]||0;
        var min = b[1]||0;    
        return a + intVal(hours*60)+intVal(min);
        }, 0);
        totalhrs  = Math.floor(totalhrs  / 60)+"." + totalhrs % 60;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download