Question

I have an html table like that :

time | time_diff
12:01| 
12:21|
12:31|

how could I calculate time_diff using Javascript (with or without jQuery) so my table looks like :

time | time_diff
12:01| 20
12:21| 10
12:31| 

I'm basically wondering how I can achieve multi lines operations on an html table?

Was it helpful?

Solution

Maybe something like this:

$('table tbody tr').each(function () {

    var $row = $(this),
        $nextRow = $row.next();

    if ($nextRow.length) {
        this.cells[1].innerHTML = timeDiff($nextRow.find('td').text(), $row.find('td').text());
    }
});

function timeDiff(t1, t2) {
    t1 = t1.split(':');
    t2 = t2.split(':');
    var diff = (t1[0] * 60 + +t1[1]) - (t2[0] * 60 + +t2[1]),
        hours = Math.floor(diff / 60),
        minutes = (diff - hours * 60) + '';
    return hours + ':' + (minutes.length == 1 ? '0' + minutes : minutes);
}

Demo: http://jsfiddle.net/vJNa4/1/

OTHER TIPS

Something like this...

function set(i, val) { sets value of seconds column, row i }
function get(i) {returns time from first column, row i;}
function diff(time1, time2) { returns difference }

last = '';
for(i=0,i<rows;i++){
 if(i>0) set(i-1, diff(get(i), last));
 last = get(i);
}

Sample implementation:

function set(i, val) { 
   $('table tr:eq('+(i+1)+' td:eq(2))').text(val); 
}
function get(i) { 
  return $('table tr:eq('+(i+1)+' td:eq(1))').text();
}
function diff(time1, time2) {
  var s1 = time1.split(':');
  var s2 = time2.split(':');
  return s1[0]*60+s1[1] - (s2[0]*60+s2[1]); 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top