从时间戳获得部分秒差异

时间:2017-04-24 16:28:07

标签: java

我有一个基本上记录数据的代码,截至目前一切似乎都运行良好,除了我在两个时间戳之间遇到问题:

System.out.println(readings.size());
    displayLog.appendText("Getting ready to print! Beep Boop! \n" );

            for (int t = 0; t < readings.size(); t++)
    {
        displayLog.appendText("Time: " + readings.get(t).getTimestamp() + " CH1: " + readings.get(t).getValue(0) + " CH2: " + readings.get(t).getValue(1) + " CH3: " + readings.get(t).getValue(2) + " CH4: " + readings.get(t).getValue(3) + " CH5: " + readings.get(t).getValue(4) + " CH6: " + readings.get(t).getValue(5) + " CH7: " + readings.get(t).getValue(6) + " CH8: " + readings.get(t).getValue(7) + " CH9: " + readings.get(t).getValue(8) + "\n");
    }
            int maxReading = readings.size() - 1;
            displayLog.appendText(readings.get(0).getTimestamp() + "\n");
            displayLog.appendText(readings.get(maxReading).getTimestamp() + "\n");

            Duration timeDifference = Duration.between(readings.get(0).getTimestamp(), readings.get(maxReading).getTimestamp());

            displayLog.appendText("Time difference is: " + timeDifference.getSeconds() + "\n");

每当我运行代码时,我得到一个整数,是否有一种方法可以像显示部分秒的双倍? 说6.3秒或8.8秒而不是6和9.我甚至不知道它是向上舍入还是向下舍入或截断,或者当它返回此值时它会做什么?还是有更好的方法来获得时差?

使用timeStamp LocalDateTime.now()按下按钮记录时间戳

我尝试使用此代码进行打印并查看,但结果不一致:

    int maxReading = readings.size() - 1;
    Duration timeDifference = Duration.between(readings.get(0).getTimestamp(), readings.get(maxReading).getTimestamp());
    double secondsDifference = timeDifference.getNano() / 1000000000;
    textLog.appendText("Total time logged is: " + secondsDifference + "\n");
    System.out.println(timeDifference.getSeconds() + "  |  " + secondsDifference + "  |  " + timeDifference.getNano());
    System.out.println("Time logged: " + secondsDifference);

然而,这给出了以下输出,这是没有意义的(IMO):

4  |  0.0  |  270000000
Time logged: 0.0

就像这样它记录了4秒钟?或者是270000000纳秒? 或者它实际上是4.27秒?

1 个答案:

答案 0 :(得分:1)

如果您在应用DST更改时记录内容,或者您​​的计算机因任何原因更改了时区,我建议您使用Instant.now()

获得&#34;十进制&#34;秒数,您可以使用:

Duration d = ...;
double seconds = d.toNanos() / 1e9d;

然后,您可以将结果附加为字符串,并带有所需的小数位数 - 例如,您想要2位小数:

String twoDecimals = String.format("%.2f", seconds);