You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Current »

In this article, I'll show you how to calculate the difference in time in a spreadsheet. In this method, we will use Javascript to calculate the variable.

Form Design


Custom HTML

This is the Javascript code that contains the function to calculate the Time Difference variable.

Javascript
<script>
function timediff(start, end) {
    if (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);

        // 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;
    } else {
        return "";
    }
}
</script>

Runtime

This is the result of the above code when you launch the app.


Download The Sample App

  • No labels