假设我有long currentMillis和long oldMillis。这两个时间戳之间的差别非常小,而且总是小于1秒。
如果我想知道时间戳之间的差别(以毫秒计),可以执行以下操作:
长差=现在的-旧的;
如果我想把差转换成秒,我可以把它除以1000。但是,如果以毫秒为单位的差小于1000毫秒(<1秒),除以1000将得到0。
如果两个时间戳的差小于1秒,我如何才能得到这个时间戳之间的差异?例如,如果差为500毫秒,则所需输出为0.5秒。
使用float/double而不是long总是返回0.0,原因我不明白。
我的代码:
private long oldmillis = 0, difference = 0;
private long calculateDifference()
{
long currentMillis = System.currentTimeMillis();
if (oldMillis == 0) oldMillis = currentMillis;
difference = currentMillis - oldMillis;
oldMillis = currentMillis;
return difference;
}该方法是随机调用的,具有小的随机时间间隔。
发布于 2014-06-11 16:59:32
听起来,您只需要在划分之前将结果转换为double:
// This will work
double differenceMillis = currentMillis - oldMillis;
double differenceSeconds = differenceMillis / 1000;
// This will *not* work
double differenceSecondsBroken = (currentMillis - oldMillis) / 1000;在后一段代码中,使用整数算法执行除法,因此最终得到的结果为0,然后将其转换为double。
另一种可行的方法是将1000.0除以1000.0,这将强制使用浮点数进行算术:
double differenceSeconds = (currentMillis - oldMillis) / 1000.0;https://stackoverflow.com/questions/24168492
复制相似问题