For some reason I am getting a consistent 3600 returned by the function:
private static long getCountdownLeft() {
long now = System.currentTimeMillis();
This is most probably because the elapsedMillis
is coming as zero. I would suggest using System.nanoTime()
for calculating elapsed time.
I'm not so sure how your code works (as is posted right now), but something like this might work. Note that you need to add your logic for computation, this is just a sample:
public class TimeTest {
private long startTime;
public TimeTest(){
startTime = System.nanoTime();
}
public void computeTimeDifference(){
long currentTime = System.nanoTime();
long elapsedTime = currentTime - startTime;
System.out.println("Difference: "+elapsedTime+ "ns");
}
public static void main(String[] args) {
new TimeTest().computeTimeDifference();
}
}
Your code will consume little time before invoke getCountdownLeft. try update this code :
public static void Main(String[] args) throws InterruptedException {
long gameTime = System.currentTimeMillis(); // pass the current time
Thread.currentThread().sleep(1000); // sleep one second before invoke getCountdownLeft
System.out.println("Time is " + getCountdownLeft(gameTime));
}
Hey I have just added print statements for prev, new and elapsed variables. The values are
previous time 1343882409054
present time 1343882409054
elapsed time 0
Time is 3600
So your millisLeft will always be 3600 .
But if you try using
System.nanoTime()
the values are,
previous time 519222175869357
present time 519222175923421
elapsed time 54064
Time is 3545
So you have to be more granular here and consider using System.nanoTime().