2016-08-11 28 views
4

我已经在分钟的格式设置的三次时间:秒:毫秒,我需要以加在一起,并获得总时间..添加行值

例如我用的一个是:0:31.110 + 0:50.490 + 0:32.797 其中= 1:54.397

所以如何做到这一点在JavaScript?

这里是JS代码

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); 

我不知道从哪里开始,但我刚刚想出了上面的代码.. 我需要的输出为1:在过去的54.397 td,但是我得到这个例子中显示的0:31.1100:50.4900:32.797 http://jsfiddle.net/q1kumbea/

+1

以及您希望阵列添加尽可能多的数字,你可以简单地用分割法打破它和做数学题 – aw04

+0

你需要拆分时间,然后单独添加每个组件,如t1.split(“:”),t2.split(“:”),t3.split(“:”),然后t1 [0] + t2 [0] + t3 [0 ] ...并在结尾再次加入冒号(:) – atul

回答

6

你可以使用moment.js这个。这将使它很容易,因为你可以解析的时间以正确的格式,添加moments在一起......

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")); 

...瞧

enter image description here

Updated fiddle

+0

完美!正是我想要的。 – skyline33

+0

太棒了! @ skyline33 – baao

+0

您可能想为日期格式使用变量,因此您不必重复它。 –

3

我不知道任何本地功能,但你总是可以(几乎:))使用一些数学来实现你想要的。像下面

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" 

可以,除非你把它们的格式相同

+0

不错,这也适用--- http://jsfiddle.net/q1kumbea/2/ – skyline33