tags:

views:

28

answers:

2

I have to calculate the interval from time duration in javascript. ie, if 100:56:56 to 101:00:00, then duration is 0 hr 3 mins 4 secs .

How to do this in javasript?

+1  A: 

In Javascript you can do maths on a Date object.

var
  date1 = new Date(2010, 07, 07, 05, 00, 00),
  date2 = new Date(2010, 07, 21, 15, 30, 00);

return (date2 - date1);

This will return the number of milliseconds between the two dates.

You could then convert that to hours, minutes and seconds if you wanted by dividing by 86400000 for days, then divide the remainder of that by 3600000 for hours, then the remainder of that by 60000 for minutes, etc.

thomasrutter
hello thomasHere I am not dealing with date.... here dealing with tape time positions. so big hr position can come 100th hr to 112 hr can come
nithin alex
Hmmm does it work if you put in, for example, new Date(0, 0, 0, 100, 56, 56) ? Although I get what you mean this may still be a workaround.
thomasrutter
no ... it is not working !!!
nithin alex
+1  A: 
function Time (hour, min, sec) {
  this.hour = hour;
  this.min = min;
  this.sec = sec;
}

Time.parse = function (str) {
  var arr = str.split (":");
  return new Time (arr [0], arr [1], arr [2]);
};

Time.prototype = {
    constructor: Time

  , toString: function () {
      return [this.hour, this.min, this.sec].join (":");
    }

  , toSec: function () {
      return this.hour * 3600 + this.min * 60 + this.sec;
    }

  , toMillSec: function () {
      return this.toSec () * 1000;
    }

  , subtract: function (time) {
      diff = new Time (
          this.hour - time.hour
        , this.min - time.min
        , this.sec - time.sec
      );
      if (diff.sec < 0) {
        diff.sec += 60;
        --diff.min;
      }
      if (diff.min < 0) {
        diff.min += 60;
        --diff.hour;
      }
      return diff;
    }
};

var t1 = Time.parse ("101:00:00");
var t2 = Time.parse ("100:56:56");
var t3 = t1.subtract (t2);

t3.toString (); // "0:3:4"
t3.toMillSec (); // 184000
trinithis