Calculate timespan in JavaScript

I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows:

txtStart.Text = 09/19/2008 07:00:00

txtEnd.Text = 09/19/2008 05:00:00

I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page.

Answers:

Answer

Once your textbox date formats are known in advance, you can use Matt Kruse's Date functions in Javascript to convert the two to a timestamp, subtract and then write to the resulting text box.

Equally the JQuery Date Input code for stringToDate could be adapted for your purposes - the below takes a string in the format "YYYY-MM-DD" and converts it to a date object. The timestamp (getTime()) of these objects could be used for your calculations.

stringToDate: function(string) {
    var matches;
    if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
       return new Date(matches[1], matches[2] - 1, matches[3]);
    } else {
       return null;
    };
}
Answer
function stringToDate(string) {
        var matches;
    if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2}) (\d{2,2}):(\d{2,2}):(\d{2,2})$/)) {
       return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]);
    } else {
       return null;
    };
}

    function getTimeSpan(ticks) {
        var d = new Date(ticks);
        return {
            hour: d.getUTCHours(), 
            minute: d.getMinutes(), 
            second: d.getSeconds()
        }
    }

    var beginDate = stringToDate('2008-09-19 07:14:00');
    var endDate = stringToDate('2008-09-19 17:35:00');

    var sp = getTimeSpan(endDate - beginDate);
    alert("timeuse?" + sp.hour + " hour " + sp.minute + " minute " + sp.second + " second ");

you can use getUTCHours() instead Math.floor(n / 3600000);

Answer

I took what @PConroy did and added to it by doing the calculations for you. I also added the regex to make sure the time is part of the string to create the date object.

<html>
    <head>
        <script type="text/javascript">
            function stringToDate(string) {
                var matches;
                if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2}) (\d{2,2}):(\d{2,2}):(\d{2,2})$/)) {
                   return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]);
                } else {
                   return null;
                };
            }

            //Convert duration from milliseconds to 0000:00:00.00 format
            function MillisecondsToDuration(n) {
                var hms = "";
                var dtm = new Date();
                dtm.setTime(n);
                var h = "000" + Math.floor(n / 3600000);
                var m = "0" + dtm.getMinutes();
                var s = "0" + dtm.getSeconds();
                var cs = "0" + Math.round(dtm.getMilliseconds() / 10);
                hms = h.substr(h.length-4) + ":" + m.substr(m.length-2) + ":";
                hms += s.substr(s.length-2) + "." + cs.substr(cs.length-2);
                return hms;
            }

            var beginDate = stringToDate('2008-09-19 07:14:00');
            var endDate = stringToDate('2008-09-19 17:35:00');

            var n = endDate.getTime() - beginDate.getTime();

            alert(MillisecondsToDuration(n));
        </script>
    </head>
    <body>
    </body>
</html>

This is pretty rough, since I coded it up pretty fast, but it works. I tested it out. The alert box will display 0010:21:00.00 (HHHH:MM:SS.SS). Basically all you need to do is get the values from your text boxes.

Answer

The answers above all assume string manipulation. Here's a solution that works with pure date objects:

var start = new Date().getTime();
window.setTimeout(function(){
  var diff = new Date(new Date().getTime() - start);
  // this will log 0 hours, 0 minutes, 1 second
  console.log(diff.getHours(), diff.getMinutes(),diff.getSeconds());
},1000);
Answer

I googled for calculating a timespan in javascript and found this question on SO; unfortunately the question text and actual question (only needing hours and minutes) are not the same... so I think I arrived here in error.

I did write an answer to the question title, however - so if anyone else wants something that prints out something like "1 year, and 15 minutes", then this is for you:

function formatTimespan(from, to) {
    var text = '',
        span = { y: 0, m: 0, d: 0, h: 0, n: 0 };

    function calcSpan(n, fnMod) {
        while (from < to) {
            // Modify the date, and check if the from now exceeds the to:
            from = from[fnMod](1);
            if (from <= to) {
                span[n] += 1;
            } else {
                from = from[fnMod](-1);
                return;
            }
        }
    }

    function appendText(n, unit) {
        if (n > 0) {
            text += ((text.length > 0) ? ', ' : '') +
                n.toString(10) + ' ' + unit + ((n === 1) ? '' : 's');
        }
    }

    calcSpan('y', 'addYears');
    calcSpan('m', 'addMonths');
    calcSpan('d', 'addDays');
    calcSpan('h', 'addHours');
    calcSpan('n', 'addMinutes');

    appendText(span.y, 'year');
    appendText(span.m, 'month');
    appendText(span.d, 'day');
    appendText(span.h, 'hour');
    appendText(span.n, 'minute');

    if (text.lastIndexOf(',') < 0) {
        return text;
    }

    return text.substring(0, text.lastIndexOf(',')) + ', and' + text.substring(text.lastIndexOf(',') + 1);
}
Answer

Use Math.floor(n / 3600000) instead of getUTCHours() or else you would lose the number of hours greater than 24.

For example, if you have 126980000 milliseconds, this should translate to 0035:16:20.00

If you use getUTCHours() you get an incorrect string 0011:16:20.00

Better instead, use this (modifications denoted by KK-MOD):

function MillisecondsToDuration(n) {
var hms = "";
var dtm = new Date();
dtm.setTime(n);
var d = Math.floor(n / 3600000 / 24); // KK-MOD
var h = "0" + (Math.floor(n / 3600000) - (d * 24)); // KK-MOD
var m = "0" + dtm.getMinutes();
var s = "0" + dtm.getSeconds();
var cs = "0" + Math.round(dtm.getMilliseconds() / 10);
hms = (d > 0 ? d + "T" : "") + h.substr(h.length - 2) + ":" + m.substr(m.length - 2) + ":"; // KK-MOD
hms += s.substr(s.length - 2) + "." + cs.substr(cs.length - 2);
return hms; }

So now, 192680000 gets displayed as 1T11:16:20.00 which is 1 day 11 hours 16 minutes and 20 seconds

Answer

I like the K3 + KK-MOD approach, but I needed to show negative timespans, so I made the following modifications:


function MillisecondsToDuration(milliseconds) {
   var n = Math.abs(milliseconds);
   var hms = "";
   var dtm = new Date();
   dtm.setTime(n);
   var d = Math.floor(n / 3600000 / 24); // KK-MOD
   var h = "0" + (Math.floor(n / 3600000) - (d * 24)); // KK-MOD
   var m = "0" + dtm.getMinutes();
   var s = "0" + dtm.getSeconds();
   var cs = "0" + Math.round(dtm.getMilliseconds() / 10);
   hms = (milliseconds < 0 ? " - " : "");
   hms += (d > 0 ? d + "." : "") + h.substr(h.length - 2) + ":" + m.substr(m.length - 2) + ":"; // KK-MOD
   hms += s.substr(s.length - 2) + "." + cs.substr(cs.length - 2);
   return hms; }

I also changed the 'T' separator to a '.' for my own formatting purposes.

Now a negative value passed in, say -360000 (negative six minutes) will produce the following output:

- 00:06:00

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.