为什么纳秒必须在 java 中使用 int 而不是 long

why nano seconds have to use int instead of long in java

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

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

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

那是因为就像 documentation 说的,我们有一个持续时间,它由两个字段组成,一个是秒,另一个是纳秒。 因此,当您要求持续时间介于两者之间时,您会得到 2 个值:

diff = seconds + nanos

所以在这种情况下,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