2017-04-24 62 views
1

我有一个基本记录的数据,截至目前一切似乎除了我有收到两个时间戳之间的差异问题,是工作的罚款代码:获取从时间戳偏秒差

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()按钮登录

我想这个代码打印看看,但我得到inconsisten结果:

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); 

然而,这给了以下输出,这是没有道理(国际海事组织):

4 | 0.0 | 270000000 
Time logged: 0.0 

像,根据它记录4秒?或270000000纳秒? 或者它实际上是4.27秒?

回答

1

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

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

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

您可以将结果再追加为一个字符串,与所需的小数位数的 - 说你要2位小数:

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

什么是toNanos()返回?我的意思是假设整体持续时间是6.4秒,那会给我6400000000吗?如果我想用它来进行其他计算?然后我解析它加倍?是不是像低效? (字符串然后加倍) –

+0

是,6.4秒,以纳秒为单位。如果您将其用于其他计算,则使用double而不是字符串。我刚刚从你的代码示例开始。 – assylias

+0

请注意,getSeconds返回持续时间的“秒”部分,即它被截断。 – assylias