计算从时间差到总工作时间

时间:2013-12-12 05:53:46

标签: jquery math logic jquery-calculation

我需要计算时差24小时。 代码

中似乎有些不对劲
if ( shiftToMin >= shiftFromMin ){
        shiftTotalMin = shiftToMin - shiftFromMin;
        if( shiftFromHr < shiftToHr ){
            shiftTotalHr = shiftToHr - shiftFromHr;
        }else{
            shiftTotalHr = ( 24 - shiftFromHr ) + shiftToHr;
        }
    }else{
        shiftTotalMin = 60 - ( shiftFromMin - shiftToMin );
        if( shiftFromHr < shiftToHr){
            shiftTotalHr = ShiftToHr - shiftFromHr; 
        }else{
            shiftTotalHr = ( 24 - shiftFromHr ) + shiftToHr;
        }
        shiftTotalHr = shiftTotalHr - 1;
    }

3 个答案:

答案 0 :(得分:1)

向我们展示您的full code,了解您是否希望calculate time difference two dates试试这个,

function time_diff(start, end) {
    sdate = new Date(start);edate = new Date(end);
    var sd = [];var ed = [];
    sd[0] = sdate.getFullYear();
    sd[1] = sdate.getMonth();
    sd[2] = sdate.getDate();
    sd[3] = sdate.getHours();
    sd[4] = sdate.getMinutes();
    ed[0] = edate.getFullYear();
    ed[1] = edate.getMonth();
    ed[2] = edate.getDate();
    ed[3] = edate.getHours();
    ed[4] = edate.getMinutes();
    var startDate = new Date(sd[0], sd[1], sd[2], sd[3], sd[4], 0);
    var endDate = new Date(ed[0], ed[1], ed[2], ed[3], ed[4], 0);
    var diff = endDate.getTime() - startDate.getTime();
    var hours = Math.floor(diff / 1000 / 60 / 60);
    diff -= parseInt(hours) * 1000 * 60 * 60;
    var minutes = Math.floor(diff / 1000 / 60);
    if (hours < 0) {
        return 'error';
    }
    return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}
alert(time_diff('12/11/2013 10:25:00', '12/12/2013 11:25:00'));
alert(time_diff('12/12/2013 10:25:00', '12/12/2013 11:50:00'));

Demo

答案 1 :(得分:1)

使用getTime构造函数的date方法。它给出了通过的总毫秒数(自1970年以来,我认为)

var shiftStart = new Date(0,0,0,shiftFromHour,shiftFromMin); 
var shiftEnd = new Date(0,0,0,shiftToHour,shiftToMin);    
var msDiff = shiftEnd.getTime()-shiftStart.getTime();
var hours = Math.floor(msDiff/(1000*60*60));

hours将包含shiftStartshiftEnd之间的工作小时数(均为Date个实例)

答案 2 :(得分:0)

工作和工作

// Time Difference Cal
        if ( shiftFromHr <= shiftToHr ){
            shiftTotalHr = shiftToHr - shiftFromHr;
        }else{
            shiftTotalHr = ( 24 - shiftFromHr ) + shiftToHr;
        }

        if ( shiftFromMin <= shiftToMin ){
            shiftTotalMin = shiftToMin - shiftFromMin;
        }else{
            shiftTotalMin = 60 - ( shiftFromMin - shiftToMin );
            shiftTotalHr = shiftTotalHr - 1;
        }
// Total time difference shiftTotalHr : shiftTotalMin

全部谢谢:)