在Javascript中添加HH:MM:SS字符串 [英] Adding HH:MM:SS strings in Javascript

查看:120
本文介绍了在Javascript中添加HH:MM:SS字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我自己无法解决这个问题。
假设我有一个HH:MM:SS ex字符串格式的时间。 10:11:06 ,我想再添加一次并以字符串形式返回。例如 10:11:06 + 11:00:01将返回 21:11:07

I don't think I can figure this out on my own. Lets say I have a time in the string format of HH:MM:SS ex. 10:11:06 and I would like to add another time to it and return it as a string. ex. "10:11:06" + "11:00:01" would return "21:11:07"

我浏览了这个网站,提出了一种解决方案,将其转换为秒,然后将它们像这样添加在一起:

I have gone through this site coming up with a solution of converting it to seconds and then adding them together as such:

function addTimes(start, end) {
 var a = start.split(":");
 var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 
 var b = end.split(":");
 var seconds2 = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]); 

 var date = new Date(1970,0,1);
     date.setSeconds(seconds + seconds2);

 var c = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
     return c;
     console.log(c);
}   

console.log C返回无效日期。这是字符串还是我做错了?

Yet console.log C returns an Invalid Date. Is this still a string or am I doing something wrong?

来源1 来源2

编辑:(我很愚蠢)我在递归循环中遇到了这个问题,我用 var s = 0; 而不是 var s = 00:00:00;

(I was stupid) I had this in a recursive loop and I initialized the sum variable with a var s = 0; instead of a var s = "00:00:00";

推荐答案

尝试一下

var start = "10:11:06";
var end = "10:11:06";
  var a = start.split(":");
 var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 
 var b = end.split(":");
 var seconds2 = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]); 

 var date = new Date(1970,0,1);
     date.setSeconds(seconds + seconds2);

 var c = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
console.log(c);

这篇关于在Javascript中添加HH:MM:SS字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆