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?
CodePudding user response:
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
CodePudding user response:
getNano() JavaDocs:
Returns:
the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999
CodePudding user response:
It's because it's hard for computers to deal with non-integer values. Besides, you can always just divide by 1 000 000 000 to get the value in seconds.