开发者

java milliseconds find closest to current time

I have开发者_JAVA百科 following code:

for(int i=0; i<a.length; i++){
    diff[i] = a.getTime() - b.getTime();
}

a.getTime() = time in array.
b.getTime() = current time on computer.

What would be the best way to find which one of a.getTime is nearest to current time?

Output diff:

-143214521
32942394
-132931
-21340


Just keep the absolute value of the difference (using Math.abs), and keep track of the minimum value you've seen so far, along with the index at which it occurred.

For example:

long currentTime = b.getTime(); // Only call once, to be consistent
long minAbsDiff = Long.MAX_VALUE;
int minIndex = -1;
for(int i=0; i < a.length; i++) {
    diff[i] = a[i].getTime() - currentTime;
    long abs = Math.abs(diff[i]);
    if (abs < minAbsDiff) {
        minAbsDiff = abs;
        minIndex = i;
    }
}

This is assuming you still need diff[i] elsewhere. If you don't, and if you only need the a value with the minimum difference, you can write it more compactly:

long currentTime = b.getTime(); // Only call once, to be consistent
long minAbsDiff = Long.MAX_VALUE;
WhateverType minContainer = null;
for (WhateverType x : a) {
    long abs = Math.abs(x.getTime() - currentTime);
    if (abs < minAbsDiff) {
        minAbsDiff = abs;
        minContainer = x;
    }
}


Do Math.abs(long) on each of the results and use the lowest one.

(Create an array of type long[], put the abs() values inside and then sort it using Arrays.sort())

BTW, you probably want to do b.getTime() only once.


long min = Long.MAX_VALUE;
long current = b.getTime();
int index = -1;
for(int i=0; i<a.length; i++) {
   long diff = Math.abs(current - a.getTime());
   if(diff < min) {
     min = diff;
     index = i;
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜