How can I calculate the difference between two times that are in 24 hour format?

后端 未结 5 1889
死守一世寂寞
死守一世寂寞 2020-12-01 18:23

In JavaScript, how can I calculate the difference between two times that are in 24 hour format?

Example: Get how many hours elapsed from 08:00:00 to

5条回答
  •  抹茶落季
    2020-12-01 18:56

    I changed your code to just use the difference without having to create another date object:

    $(document).ready(function() {    
    function calculateTime() {
            //get values
            var valuestart = $("select[name='timestart']").val();
            var valuestop = $("select[name='timestop']").val();
    
             //create date format          
             var timeStart = new Date("01/01/2007 " + valuestart);
             var timeEnd = new Date("01/01/2007 " + valuestop);
    
             var difference = timeEnd - timeStart;             
    
             difference = difference / 60 / 60 / 1000;
    
    
        $("p").html("Hour Difference: " + difference)             
    
    }
    $("select").change(calculateTime);
    calculateTime();
    });​
    

提交回复
热议问题