Skip to content
Advertisement

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

Doesnt nanoseconds have to use long instead of int because the nanoseconds in the range?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement