计算两次之间的时差javascript [英] Calculate time difference between two times javascript

查看:152
本文介绍了计算两次之间的时差javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过如何做到这一点,我发现了很多代码复杂的例子。
我使用这个:

  var time1 = new Date(); 
var time1ms = time1.getTime(time1); //我得到的时间在$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ >

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

最后:

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

这是非常好的,除了一个问题,它吸引我的时间总是+1,所以我有添加到代码(time.getHours() - 1)否则它给我一个小时更多....



我认为是一个比其他所有例子更简单的方法...但是我仍然不明白为什么我需要添加'-1'才能有正确的失效。



THanks !!!

解决方案

问题是您的时区。



当您执行新日期(差异)时,您正在创建一个 Date 对象,表示时刻ex code>差异 1970年1月1日之后的毫秒。当您执行 puts.getHours()时,您的时区用于计算。您不能通过Javascript修改您的时区,也不能修改此行为。不是没有一些重的 Javascript技巧。



但是您的差异 代表日期,但日期的差异。治疗是这样的,并计算这样的小时,分​​钟和秒数:

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

或者,您可以在创建流失

  var elapsed = new Date(difference + new Date()。getTimezoneOffset()* 1000); 

但我不会推荐这个:日期对象为您的目的是过度的。


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!!!

解决方案

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.

这篇关于计算两次之间的时差javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆