-1

開始時刻と終了時刻を使用して期間を計算したい。

時間を取得するコードがありますが、時間と分の両方が必要です。

コードにどのような変更を加える必要がありますか?

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

3 に答える 3

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;
于 2012-12-28T09:51:31.133 に答える
0

Moment.jsの使用を検討してください。これにより、作業が楽になります。

于 2012-12-28T09:38:19.263 に答える
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));​
于 2012-12-28T10:18:25.873 に答える