Search code examples
javascriptdatedatetimedhtmlx

Calculate Hours Between two Date/Time Strings(YYYY-mm-dd HH:MM:SS) using Javascript


I have two Time Stamps in the following Format:

Start Time  - 2016-01-01 00:00:00 
Finish Time - 2016-01-02 23:15:00

I need to calculate the number of hours between the two date times correct to two decimal places.

I need the result to be in the following format

Hrs = 47.25

This would be 23 hours and .25 of an hour not 25 mins, I do not need to round to the nearest 15 I only need to round to 2 decimal places.

Any Help shall be much appreciated. This data will then be inserted back into a cell in a DHTMLX grid.

FINAL SOLUTION

adminGrid.attachEvent("onEditCell",function(stage,rId,cInd,nValue,oValue){
                if ((cInd == colStartTime || cInd == colFinishTime) && stage == 2) {
                    var startTime = new Date(adminGrid.cells(rId,colStartTime).getValue());
                    var finishTime = new Date(adminGrid.cells(rId,colFinishTime).getValue());
                    var Hrs = ((finishTime - startTime)/1000/60/60).toFixed(2);
                    adminGrid.cells(rId,colHrs).setValue(Hrs);                      
                }
                return true;
            });

Solution

  • var startDate = new Date('2016-01-01 00:00:00');
    var endDate = new Date('2016-01-02 23:15:00');
    var time = endDate - startDate;
    console.log(time/1000/60/60%24); //23.25
    

    like this can calculate the hours span.