Reputation: 23
For some reason I am getting a consistent 3600 returned by the function:
private static long getCountdownLeft() {
long now = System.currentTimeMillis();
long elapsedMillis = now - initialTime; //difference of current 'current' time
long millisLeft = secondsOfGame * 1000 - elapsedMillis;
return millisLeft/1000;
}
public static void Main(String[] args ) {
System.out.println("Time is " + getCountdownLeft());
}
private static int secondsOfGame = 3600;
private static long initialTime = System.currentTimeMillis();
This is event driven. I expect to see a difference in time everytime I invoke the function. I just use main to show that I am invoking it.
Upvotes: 3
Views: 2030
Reputation: 3288
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().
Upvotes: 0
Reputation: 6783
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();
}
}
Upvotes: 2
Reputation: 1241
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));
}
Upvotes: 0