Search code examples
javadatedate-difference

How do I get the date difference as a floating-point number with millisecond precision


public static void main(String[] args) throws InterruptedException{
    long sTime =  new Date().getTime();
    Thread.sleep(3234);
    long eTime =  new Date().getTime();
    float diff = ((eTime-sTime)/1000);
    System.out.println(diff);
}

In the above code, I am expecting the output to be 3.234 but it is 3.0. I want the exact difference between two times in seconds, with a fractional part.


Solution

  • You are doing an integral division instead of a floating-point one. Try this:

    float diff = ((float)(eTime-sTime)/1000.0);
    

    As you are using longs, I further suggest you to use double datatype for greater precision:

    double diff = ((double)(eTime-sTime)/1000.0);