Question

I need to calculate time difference 24Hrs Time. some thing seems wrong in the code

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;
    }
Was it helpful?

Solution 3

Worked out and working

// 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

Thanks All :)

OTHER TIPS

Show us your full code to understand if you want to calculate the time difference from two dates the try this,

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

Use the getTime method of the date constructor. It gives the total number of milliseconds passed(since 1970, I think)

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 would contain the number of working hours between shiftStart and shiftEnd (both being Date instances)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top