Calculate Time Difference with JavaScript

后端 未结 12 1146
有刺的猬
有刺的猬 2020-12-01 13:20

I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.

F

12条回答
  •  忘掉有多难
    2020-12-01 13:47

    This is an updated version of one that was already submitted. It is with the seconds.

    function diff(start, end) {
        start = start.split(":");
        end = end.split(":");
        var startDate = new Date(0, 0, 0, start[0], start[1], 0);
        var endDate = new Date(0, 0, 0, end[0], end[1], 0);
        var diff = endDate.getTime() - startDate.getTime();
        var hours = Math.floor(diff / 1000 / 60 / 60);
        diff -= hours * (1000 * 60 * 60);
        var minutes = Math.floor(diff / 1000 / 60);
        diff -= minutes * (1000 * 60);
        var seconds = Math.floor(diff / 1000);
    
        // If using time pickers with 24 hours format, add the below line get exact hours
        if (hours < 0)
           hours = hours + 24;
    
        return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes + (seconds<= 9 ? "0" : "") + seconds;
    }
    

    My Updated Version:

    Allows for you to convert the dates into milliseconds and go off of that instead of splitting.

    Example Does -- Years/Months/Weeks/Days/Hours/Minutes/Seconds

    Example: https://jsfiddle.net/jff7ncyk/308/

提交回复
热议问题