Why am I getting +1 hour when calculating time difference in javascript?

I am trying to create a very simple calculation of the time difference. Just "end time - start time." I get +1 hour. I suspect this is due to my time zone, since I am GMT + 1.

Regardless of the fact that this should not affect the difference, since the start and end times are in the same time zone.

Check out the below code example:

http://jsfiddle.net/kaze72/Rm3f3/

$(document).ready(function() { var tid1 = (new Date).getTime(); $("#tid").click(function() { var nu = (new Date).getTime(); var diff = new Date(nu - tid1); console.log(diff.getUTCHours() + ":" + diff.getUTCMinutes() + ":" + diff.getUTCSeconds()); console.log(diff.toLocaleTimeString()); }); }) 
+2
javascript time
Dec 15 '12 at 16:01
source share
1 answer

You need to understand what a Date object represents and how it stores dates. Basically, each Date is a thin shell around the number of milliseconds since 1970 (the so-called era time). Subtracting one date from another, you do not get the date: you just get the number of milliseconds between them.

Assuming this line doesn't make much sense:

 var diff = new Date(nu - tid1); 

What you really need:

 var diffMillis = nu - tid1; 

... and then just extract seconds, minutes, etc .:

 var seconds = Math.floor(diffMillis / 1000); var secondsPart = seconds % 60; var minutes = Math.floor(seconds / 60); var minutesPart = minutes % 60; var hoursPart = Math.floor(minutes / 60); //... console.log(hoursPart + ":" + minutesPart + ":" + secondsPart); 

Working script .

+8
Dec 15 '12 at 16:10
source share



All Articles