html - Getting time difference between two times in javascript -


this question has answer here:

i have tried time difference between 2 different times , getting correctly hours , minutes. if second greater first getting problem. time displaying negative data.

for example

start time : 00:02:59 end time   : 00:05:28 

if getting difference between start , end time

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

which not correct value. i'm using following script getting 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 time difference between 2 times correctly considering seconds

try doing this

    var date1 = new date(2000, 0, 1,  9, 0); // 9:00     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 convert milliseconds hour, minute , seconds 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 

Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -