我想用开始时间和结束时间计算持续时间。
我有一个能让我获得时间的代码,但我也需要时间和分钟。
我应该对代码做出哪些更改?
function timeDiff( first, second ) {
var f = first.split(' '), s = second.split(' ');
if( first == '12 AM' ) f[0] = '0';
if( first == '12 PM' ) f[1] = 'AM';
if( second == '12 AM' ) s[0] = '24';
if( second == '12 PM' ) s[1] = 'AM';
f[0] = parseInt( f[0], 10 ) + (f[1] == 'PM' ? 12 : 0);
s[0] = parseInt( s[0], 10 ) + (s[1] == 'PM' ? 12 : 0);
return s[0] - f[0];
}
var FirstTime = '1 AM';
var SecondTime = '12 pM';
alert( timeDiff( FirstTime, SecondTime ) );
答案 0 :(得分:1)
var time1 = {hour: 12, minute: 30, second: 15};
var time2 = {hour: 13, minute: 40, second: 25};
var d1 = new Date(2000, 01, 01, time1.hour, time1.minute, time1.second);
var d2 = new Date(2000, 01, 01, time2.hour, time2.minute, time2.second);
var diff = Math.abs( ( d1.getTime() - d2.getTime() ) / 1000 ); // difference in seconds
var hours = Math.floor(diff / 3600); // number of full hours
var minutes = Math.floor(diff / 60); // number of full minutes
var seconds = diff - minutes * 60; // remaining seconds
// remaining seconds also can be obtained like this
var seconds = diff % 60;
答案 1 :(得分:0)
请考虑使用Moment.js因为它会让您的生活更轻松。
答案 2 :(得分:0)
请参阅:http://jsfiddle.net/R8URw/
function timeDiff(first, second) {
if (first === '' || second === '') {
return false;
}
var f = first.split(' '),
s = second.split(' ');
if (first == '12:00 AM') {
f[0] = '0';
}
if (first == '12:00 PM') {
f[1] = 'AM';
}
if (second == '12:00 AM') {
s[0] = '24';
}
if (second == '12:00 PM') {
s[1] = 'AM';
}
var time1 = f[0].split(':'),
time2 = s[0].split(':');
time1 = time1[0] * 3600 + time1[1] * 60;
time2 = time2[0] * 3600 + time2[1] * 60;
var td = time2 - time1,
hours = parseInt((td / 3600), 10),
minutes = parseInt(((td - hours * 3600) / 60), 10),
diff = ((hours < 10 && hours >= 0) ? ('0' + hours) : hours) + ':' + ((minutes < 10 && minutes >= 0) ? ('0' + minutes) : minutes);
return (diff);
}
和
var FirstTime = '1:00 AM';
var SecondTime = '12:09 pM';
alert(timeDiff(FirstTime, SecondTime));