Java - System.currentTimeMillis(); Not Returning Difference

后端 未结 3 1283
长发绾君心
长发绾君心 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();
        }
    }
    

提交回复
热议问题