Calculate time difference between two times javascript

余生长醉 提交于 2019-11-28 11:15:07

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.

Note that in the getTimezoneOffset() returns a value in minutes, so if you want to use the lapse, you can correct it for the timezone difference like this:

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 out the time difference in human readable form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!