Calculate time difference between two javascript

I am pondering how to do this, and I have found many examples with complex code. Im using this:

var time1 = new Date(); var time1ms= time1.getTime(time1); //i get the time in ms 

then I do it in another part of the code

 var time2 = new Date(); var time2ms= time2.getTime(time2); 

and the final:

 var difference= time2ms-time1ms; var lapse=new Date(difference); label.text(lapse.getHours()+':'+lapse.getMinutes()+':'+lapse.getSeconds()); 

This works fine, except for one problem, the clock it gives me is always +1, so I need to add the code (time.getHours () - 1) , otherwise it will give me one hour more ....

I think this is an easier way to do this than all the other examples around ... but I still don't understand why I need to add '-1' in order to have the right bandwidth.

thanks!!!

+7
source share
2 answers

The problem is your time zone.

When you execute new Date(difference) , you create a Date object that represents the moment of exatcly difference milliseconds after January 1, 1970. When you do lapse.getHours() , your time zone is used in the calculation. You cannot change your time zone through Javascript and you cannot change this behavior. Not without heavy Javascript tricks.

But your difference not a date, but a date difference. Treat as such, and calculate hours, minutes, and seconds, like this:

 var hours = Math.floor(difference / 36e5), minutes = Math.floor(difference % 36e5 / 60000), seconds = Math.floor(difference % 60000 / 1000); 

Alternatively, you can consider your time zone when creating lapse :

 var lapse = new Date(difference + new Date().getTimezoneOffset() * 1000); 

but I would not recommend this: Date objects are crowded for your purposes.

+11
source

Note that getTimezoneOffset() returns the value in minutes, so if you want to use skips, you can fix it for the difference in the time zone, for example:

 lapse = new Date(difference); tz_correction_minutes = new Date().getTimezoneOffset() - lapse.getTimezoneOffset(); lapse.setMinutes(offset_date.getMinutes() + tz_correction_minutes); 

now you can do:

 label.text(lapse.getDate()-1+' days and' +lapse.getHours()+':'+lapse.getMinutes()+':'+lapse.getSeconds()); 

to print the time difference in human readable form

+2
source

All Articles