【发布时间】:2013-08-04 16:05:25
【问题描述】:
所以基本上我有两个要添加的时间戳字符串:
a = "00:10:12";
aParts = a.split(/:/);
b = "00:30:34";
bParts = b.split(/:/);
time1 = 3600000 * parseInt(aParts[0]) + 60000 * parseInt(aParts[1]) + 1000 * parseInt(aParts[2]);
time2 = 3600000 * parseInt(bParts[0]) + 60000 * parseInt(bParts[1]) + 1000 * parseInt(bParts[2]);
dateTime = time1 + time2;
hours = parseInt(dateTime/3600000);
dateTime = parseInt(dateTime%3600000);
minutes = parseInt(dateTime/60000);
dateTime = parseInt(dateTime%60000);
seconds = parseInt(dateTime/1000);
newTime = addLeadingZeros(hours,2) + ':' + addLeadingZeros(minutes,2) + ':' + addLeadingZeros(seconds,2);
// returns correct "00:40:46"
function addLeadingZeros (n, length){
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
return n >= 0 ? zeros : "-" + zeros;
}
在写这个问题时,我设法想出了上面的代码:-) 它以某种方式工作 - 这是添加两个字符串时间戳的正确方法还是有更好的方法?
忘了提 - 我确实尝试将两个字符串转换为 Date 对象并使用 .getTime() 添加两个日期时间 - 但这给了我一个错误的日期时间。
【问题讨论】:
-
你为什么使用常规时间格式,为什么不使用以毫秒为单位返回时间的
new Date().getTime();? -
忘了提及 - 我确实尝试将两个字符串转换为 Date 对象并使用 .getTime() 添加两个日期时间 - 但这给了我一个错误的日期时间。
-
当然会,你要添加两个不同的时间(包括日期),如果你想把它们加在一起,你可以过滤掉其中一个的日期例如:
dateTime = time1 + time2%216000000; /* returns the milliseconds of the time part only (1000*60*60*60).*/跨度>
标签: javascript jquery timestamp