Java - System.currentTimeMillis(); Not Returning Difference

后端 未结 3 1286
长发绾君心
长发绾君心 2021-01-20 17:02

For some reason I am getting a consistent 3600 returned by the function:

private static long getCountdownLeft() {
    long now = System.currentTimeMillis();
         


        
相关标签:
3条回答
  • 2021-01-20 17:32

    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();
        }
    }
    
    0 讨论(0)
  • 2021-01-20 17:52

    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));
    }
    
    0 讨论(0)
  • 2021-01-20 17:55

    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().

    0 讨论(0)
提交回复
热议问题