views:

4707

answers:

6

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.

+5  A: 

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;
    };
}
ConroyP
+3  A: 

It's fairly easy to write your own function to do this. Here's one that I just wrote, with the help of W3C's date reference.

function GetTimeDiff(date1, date2) {
  dt1 = new Date(date1);
  dt2 = new Date(date2);

  var diff;

  if(dt1 > dt2) {
    diff = new Date(dt1 - dt2);
  } else {
    diff = new Date(dt2 - dt1);
  }

  return diff;
}

This will return a Date object with the difference. You can extract the different parts like so:

diff = GetTimeDiff("2001-3-1 22:00", "2001-3-1 21:30");
minutes = diff.getMinutes;
seconds = diff.getSeconds;

etc.

Vincent McNabb
This does not work. The result of new Date(new Date("2001-3-1 22:00") - new Date("2001-3-1 21:30")) is NaN.
Chris
And even if it did work, it wouldn't work, because of time zones, etc.
Robert L
This is bogus. Especially for years.
superjoe30
+1  A: 

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.

Dale Ragan
A: 

Hey folks,

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);
jvenema
A: 
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);

jassey
A: 

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

KKK