Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

date - Calculate time difference between two times javascript

i've looking around how to do this and i found a lot of examples with complicated code. Im using this:

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

then i do this in other part of the code

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

and finnally:

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

This works great, except for one issue, the hours it gaves me are always +1 so i have to add to the code (time.getHours()-1) otherwise it gaves me one hour more....

I think is an easier way to do it than all the other examples around... but i still dont understand why i need to add '-1' in order to have the correct lapse.

THanks!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is your timezone.

When you do new Date(difference), you're creating a Date object that represent the moment exatcly difference milliseconds after January 1st, 1970. When you do lapse.getHours() your timezone is used in the computation. You cannot modify your timezone via Javascript, and cannot modify this behaviour. Not without some heavy Javascript tricks.

But your difference does not represent a date, but a difference of dates. Treat is as such, and compute the 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 take your timezone into account when creating lapse:

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

but I wouldn't recommend this: Date objects are overkill for your purposes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...