Java 从时间戳中获取部分秒差

Java 从时间戳中获取部分秒差,java,Java,我有一个基本上记录数据的代码,到目前为止,一切似乎都运行良好,除了我在获取两个时间戳之间的差异时遇到问题: System.out.println(readings.size()); displayLog.appendText("Getting ready to print! Beep Boop! \n" ); for (int t = 0; t < readings.size(); t++) { displayLog.appendT

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

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");
但是,这会产生以下输出,这是没有意义的(IMO):

比如,根据这个,它记录了4秒钟?还是270000000纳秒?
或者实际上是4.27秒?

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

要获得“十进制”秒数,可以使用:

Duration d = ...;
double seconds = d.toNanos() / 1e9d;
然后,您可以将结果附加为一个字符串,带有所需的小数数-假设您需要2个小数:

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

toNanos()返回什么?我的意思是假设总的持续时间是6.4秒,那我能得到6400000000吗?如果我想用它来做其他的计算呢?然后我是否将其解析为double?这不是很低效吗?(先串,然后加倍)是的,6.4秒,以纳秒为单位。如果将其用于其他计算,则使用double,而不是字符串。我刚从您的代码示例开始。请注意,getSeconds返回持续时间的“秒”部分,即它被截断。我稍微修改了代码,发现一些不一致之处,请查看OP.@DavidBoydston,在您的示例中,您使用了
getNanos
而不是
toNanos
。持续时间是秒数加上纳秒数。在您的示例中,是4秒(getSeconds)和270000000Nano(GetNano),因此总持续时间是4.27秒,您可以使用toNanos获得。
Duration d = ...;
double seconds = d.toNanos() / 1e9d;
String twoDecimals = String.format("%.2f", seconds);