为什么在java中nano seconds必须使用int而不是long



我一直在做这个练习,这是代码

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 Nanonn",
diffInHours, diffInMinutes, diffInMilli, diffInSeconds, diffInNano );
}
}

纳秒不必须使用long而不是int,因为纳秒在范围内?

这是因为正如文档所说,我们有一个由两个字段组成的持续时间,一个是秒,另一个是纳米。所以当你请求间隔时间时,你会得到两个值:

diff = seconds + nanos

所以在这种情况下,纳米只能计数到999,999,999(0.99…

所以…

如果您需要以纳米为单位的持续时间,您必须这样做:

Long totalDurationNanos = (duration.getSeconds() * 1_000_000_000f) + duration.getNanos();

编辑:

正如在注释中提到的,对于您的情况有一个更简单的方法:

java.time.Duration.between(dateTime, dateTime2).toNanos()

ChronoUnit.NANOS.between(dateTime, dateTime2)

将输出长格式的纳秒持续时间

getNano() JavaDocs:

Returns:
the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999

相关内容

  • 没有找到相关文章

最新更新