为什么纳米秒必须使用int而不是在爪哇
我一直在进行此练习,这是
import java.time.*;
import java.util.*;
public class Exercise31 {
public static void main(String[] args){
LocalDateTime dateTime = LocalDateTime.of(2016, 9, 16, 0, 0);
LocalDateTime dateTime2 = LocalDateTime.now();
int diffInNano = java.time.Duration.between(dateTime, dateTime2).getNano();
long diffInSeconds = java.time.Duration.between(dateTime, dateTime2).getSeconds();
long diffInMilli = java.time.Duration.between(dateTime, dateTime2).toMillis();
long diffInMinutes = java.time.Duration.between(dateTime, dateTime2).toMinutes();
long diffInHours = java.time.Duration.between(dateTime, dateTime2).toHours();
System.out.printf("\nDifference is %d Hours, %d Minutes, %d Milli, %d Seconds and %d Nano\n\n",
diffInHours, diffInMinutes, diffInMilli, diffInSeconds, diffInNano );
}
}
纳秒代码不需要长时间而不是INT,因为纳秒范围内的纳秒?
I have been doing this exercise and this is the code
import java.time.*;
import java.util.*;
public class Exercise31 {
public static void main(String[] args){
LocalDateTime dateTime = LocalDateTime.of(2016, 9, 16, 0, 0);
LocalDateTime dateTime2 = LocalDateTime.now();
int diffInNano = java.time.Duration.between(dateTime, dateTime2).getNano();
long diffInSeconds = java.time.Duration.between(dateTime, dateTime2).getSeconds();
long diffInMilli = java.time.Duration.between(dateTime, dateTime2).toMillis();
long diffInMinutes = java.time.Duration.between(dateTime, dateTime2).toMinutes();
long diffInHours = java.time.Duration.between(dateTime, dateTime2).toHours();
System.out.printf("\nDifference is %d Hours, %d Minutes, %d Milli, %d Seconds and %d Nano\n\n",
diffInHours, diffInMinutes, diffInMilli, diffInSeconds, diffInNano );
}
}
Doesnt nanoseconds have to use long instead of int because the nanoseconds in the range?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那是因为 documentation 说,我们的持续时间包括两个字段,一个是秒,另一个是纳米。
因此,当您要求两者之间的持续时间时,您将获得2个值:
diff = seconds + nanos
,因此在这种情况下,纳米仅计数高达999,9999999(0.99 ...秒),因此整数就足够了。
所以...
如果您需要在纳米人中持续时间,则必须做类似的事情:
编辑:
如评论中提到的,在您的情况下有一种更简单的方法:
两者
都会
输出长期格式化的纳米秒持续时间
That's because like documentation says, we have a duration which consist of two fields, one is seconds and the other one is nanos.
So when you ask for duration between, you get 2 values :
diff = seconds + nanos
So in this case, nanos only count up to 999,999,999 (0.99... seconds), so integer is enough.
So ...
If you need duration in nanos, you'll have to do something like this :
EDIT :
As mentioned in comments, there is an easier way in your case :
Both
And
would output you long formatted nanosecond duration
getnano()Javadocs:
getNano() JavaDocs: