我有一堆动态生成的div包含一个时间字符串,例如0:03:15。这些是歌曲持续时间。 我有一个脚本将这些时间加在一起并显示时间总和,但我只能得到几小时,几分钟和几秒的工作时间。我试图获得几天,几小时,几分钟和几秒钟。
这是我的代码,其中包含了我尝试过的一些新手:
function getSeconds(time) {
var parts = time.split(":");
return parseInt(parts[0], 12) * 86400 + parseInt(parts[1], 10) * 3600 + parseInt(parts[2], 10) * 60 + parseInt(parts[3], 10);
// return parseInt(parts[0], 10) * 3600 + parseInt(parts[1], 10) * 60 + parseInt(parts[2], 10);
}
//select all the elements
var totalSeconds = $(".durationhold")
.map( function(ind, elem) { //convert the jQuery object into the array
var text = $(elem).text(); //get the text from the anchor
return getSeconds(text); //set the index to the total seconds
})
.get() //gets the array out of the jQuery object
.reduce( function(runningTotal, currentValue){ //Now to combine all the values into one
return runningTotal + currentValue; //sum up the values
},0); //The initial starting value
//Now get the hour, minutes, and seconds from the total seconds
var days = parseInt (totalSeconds / 86400 );
var hours = parseInt( totalSeconds / 3600 );
var minutes = parseInt( totalSeconds / 60 ) % 60;
var seconds = totalSeconds % 60;
//left pad numbers less than ten
if(hours<10) hours = "0" + hours;
if(minutes<10) minutes = "0" + minutes;
if(seconds<10) seconds = "0" + seconds;
$("#out").html("Total Time: " + (days + ":" + hours + ":" + minutes + ":" + seconds));
这里有一个fiddle,其中包含了一些示范时间。 是否有更快的方法来做同样的事情。可以从一个到多达5000个或更多结果。 谢谢你的帮助。
答案 0 :(得分:0)
days = 0;
if(hours > 24){
days = Math.floor(hours/24);
}
这应该可以解决问题
答案 1 :(得分:0)
如果您想快速回答,请更改
var hours = parseInt( totalSeconds / 3600 );
到
var hours = parseInt( totalSeconds / 3600 ) % 24;
出于与您在会议记录上% 60
完全相同的原因,您只对显示完整日期后剩余的小时数感兴趣。
请允许我建议一种不同的方法。我可能会对“使用库进行这样一个简单的任务”得到一些评论,但是它可能就是我要做的。对于任何与js中的时间或日期有关的事情,我总是使用moment.js,这是一个工具箱。它有一个名为duration
的对象,完全符合您的需求。
你的小提琴中的所有javascript都可以用这段代码替换(假设你先包含moment.js):
// caculate total duration
var duration = moment.duration(0);
$(".durationhold").each(function() {
duration.add($(this).text());
});
// output
var days = Math.floor(duration.asDays());
days = days + (days == 1 ? ' day ' : ' days ');
var time = moment.utc(duration.asMilliseconds()).format('H:mm:ss'); // convert to date to (ab)use it's formatting
$("#out").html("Total Time: " + days + time);
不幸的是,duration
没有format
方法,所以我必须有创意才能正确输出,但除此之外,我认为代码不言自明。如果有什么不清楚的话,请随意询问!