OneLazy
OneLazy

Reputation: 509

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!

Upvotes: 0

Views: 152

Answers (2)

Vladu Ionut
Vladu Ionut

Reputation: 8193

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;

Upvotes: 2

annoyingmouse
annoyingmouse

Reputation: 5689

I did something similar a little while ago:

$.fn.dataTable.Api.register('sumDuration()', function() {
    return this.flatten().reduce(function(a, b) {
        console.log(a);
        console.log(b);
        if (typeof a === 'string') {
            a = moment.duration(a, "HH:mm").asSeconds();
        }
        if (typeof b === 'string') {
            b = moment.duration(b, "HH:mm").asSeconds();
        }
        return a + b;
    }, 0);
});

It uses MomentJS and another plugin to display the total duration correctly, there's a demo here.

Upvotes: 0

Related Questions