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

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?



Solution 1:[1]

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 :

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

EDIT :

As mentioned in comments, there is an easier way in your case :

Both

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

And

ChronoUnit.NANOS.between(dateTime, dateTime2)

would output you long formatted nanosecond duration

Solution 2:[2]

getNano() JavaDocs:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Delta George