5

I have tried to get the time difference between 2 different times and i am getting it correctly for hours and minutes. But if the second is greater than the first it will getting the problem. The time is displaying with negative data.

for example

Start time : 00:02:59
End time   : 00:05:28

If i getting the difference between start and end time

00:05:28 - 00:02:59 = 00:3:-31

Which is not a correct value. I'm using the following script for getting this value.

var start_time = $("#startTime").val();
var end_time = $("#endTime").val();
var startHour = new Date("01/01/2007 " + start_time).getHours();
var endHour = new Date("01/01/2007 " + end_time).getHours();
var startMins = new Date("01/01/2007 " + start_time).getMinutes();
var endMins = new Date("01/01/2007 " + end_time).getMinutes();
var startSecs = new Date("01/01/2007 " + start_time).getSeconds();
var endSecs = new Date("01/01/2007 " + end_time).getSeconds();
var secDiff = endSecs - startSecs;
var minDiff = endMins - startMins;
var hrDiff = endHour - startHour;
alert(hrDiff+":"+minDiff+":"+secDiff);

anyone please tell me how to get the time difference between two times correctly even considering with seconds

Kalaiyarasan
  • 12,134
  • 8
  • 31
  • 49
  • you can convert them into seconds first or even better to miliseconds, do your arithmetic and convert them back to your format. – kangoroo Aug 26 '13 at 10:15
  • but if i do that it will affect minute also. i want to get a time with "HH:MM:SS" format – Kalaiyarasan Aug 26 '13 at 10:17
  • Recent ffmpeg versions have a `-to` option so you don't have to calculate the time for the `-t` parameter. See: http://ffmpeg.org/ffmpeg-all.html#Main-options – slhck Aug 26 '13 at 12:56
  • 1
    Check the similar post http://stackoverflow.com/questions/1787939/check-time-difference-in-javascript Hope this helps. – Arun Bertil Aug 26 '13 at 10:20

1 Answers1

-7

Try doing this

    var date1 = new Date(2000, 0, 1,  9, 0); // 9:00 AM
    var date2 = new Date(2000, 0, 1, 17, 0); // 5:00 PM
    if (date2 < date1) {
        date2.setDate(date2.getDate() + 1);
    }
    var diff = date2 - date1;
    // 28800000 milliseconds (8 hours)

You can then convert milliseconds to hour, minute and seconds like this:

    var msec = diff;
    var hh = Math.floor(msec / 1000 / 60 / 60);
    msec -= hh * 1000 * 60 * 60;
    var mm = Math.floor(msec / 1000 / 60);
    msec -= mm * 1000 * 60;
    var ss = Math.floor(msec / 1000);
    msec -= ss * 1000;
    // diff = 28800000 => hh = 8, mm = 0, ss = 0, msec = 0
Bittu
  • 387
  • 2
  • 6
  • 13