如何通过DataTable页脚计算时间

时间:2017-02-06 09:06:23

标签: javascript jquery datatables

我需要在DataTable页脚中计算时间,但我只有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>");
  }

正如您在演示中所看到的,我获得了“小时用完”列中所有行的总和,我需要的是计算它的时间。当小数位变为&gt; = 60时,它应该+1整数。说结果是23.82,应该是24.22。现在,当小数位达到一百时,它只会+1整数。

有更简单的方法吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以在reduce函数中将其转换为分钟

  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;

答案 1 :(得分:0)

我刚才做了类似的事情:

$.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);
});

它使用MomentJS和另一个插件正确显示总持续时间,有一个演示here