I have set of three times in the format of Minute:Seconds:Miliseconds which I need to add to together and get the total time..
for example the one I have used is : 0:31.110 + 0:50.490 + 0:32.797 which = 1:54.397
so how to do this in javascript?
Here is JS Code
var sp1 = $('#table tr td:nth-child(2)').text()
var sp2 = $('#table tr td:nth-child(3)').text()
var sp3 = $('#table tr td:nth-child(4)').text()
var1 = sp1 + sp2 + sp3
$('td:nth-child(5)').html(var1);
I don't know where to begin but I have just come up with the above code.. I need the output to be 1:54.397 in the last td, but I get this 0:31.1100:50.4900:32.797 shown in this example http://jsfiddle.net/q1kumbea/
You may use moment.js for this. That would make it very easy, as you can just parse the times in the correct format, add the moments
together ...
var sp1 = $('#table tr td:nth-child(2)').text()
var sp2 = $('#table tr td:nth-child(3)').text()
var sp3 = $('#table tr td:nth-child(4)').text()
var1 = moment(sp1, "mm:ss.SSS") + moment(sp2, "mm:ss.SSS") + moment(sp3, "mm:ss.SSS")
$('td:nth-child(5)').html(moment(var1).format("mm:ss.SSS"));
... and voila
Updated fiddle
I don't know any native functionality, but you can always(almost:) ) use some maths to achieve what you want. like below
var plusTimes = function(arr) {
var resultTime =0;
for(var i = 0; i < arr.length; i ++) {
resultTime += (parseInt((arr[i].split(':')[0]) * 60 * 1000) + ( parseInt(arr[i].split(':')[1].split('.')[0]) * 1000 ) + parseInt(arr[i].split('.')[1]))
}
var ms = (resultTime / 1000).toString().split('.')[1];
var sec = parseInt((resultTime / 1000).toString().split('.')[0]) % 60;
var min = (parseInt((114397 / 1000).toString().split('.')[0]) - parseInt((114397 / 1000).toString().split('.')[0]) % 60) / 60;
return min + ':' + sec + '.' + ms;
}
plusTimes(['0:31.110','0:50.490', '0:32.797']) // outputs "1:54.397"
you can add as many numbers as you wish to array unless you keep their format the same
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With