简体   繁体   English

如何以毫秒精度获取日期差作为浮点数

[英]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. 在上面的代码中,我期望输出为3.234但它是3.0。 I want the exact difference between two times in seconds, with a fractional part. 我希望在几秒钟内两次之间有确切的差异,并有一个小数部分。

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 long s, I further suggest you to use double datatype for greater precision: 当您使用long ,我进一步建议您使用double数据类型以提高精度:

double diff = ((double)(eTime-sTime)/1000.0);
    double sTime =  new Date().getTime();
    Thread.sleep(3234);
    double eTime =  new Date().getTime();
    double diff = ((eTime-sTime)/1000);
    System.out.println(diff);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM