Are the both methods equivalent?
version 1:
var diff = Duration.between(begin, end).toHours();
version 2;
var diff = ChronoUnit.HOURS.between(begin, end);
Are there any implicit differences? If yes, which one should I prefer?
Are the both methods equivalent?
version 1:
var diff = Duration.between(begin, end).toHours();
version 2;
var diff = ChronoUnit.HOURS.between(begin, end);
Are there any implicit differences? If yes, which one should I prefer?
Analyzed implementation on open JDK 15
A) Duration.between(begin, end).toHours();
Duration.between(begin, end) first calls
long until(Temporal endExclusive, TemporalUnit unit); //called with unit of NANOS or SECONDS if first one fails
and then parses the difference to create a Duration based on nanos that have been calculated (or seconds if calculation of nanos failed)
public static Duration between(Temporal startInclusive, Temporal endExclusive) {
try {
return ofNanos(startInclusive.until(endExclusive, NANOS));
} catch (DateTimeException | ArithmeticException ex) {
long secs = startInclusive.until(endExclusive, SECONDS);
long nanos;
try {
nanos = endExclusive.getLong(NANO_OF_SECOND) - startInclusive.getLong(NANO_OF_SECOND);
if (secs > 0 && nanos < 0) {
secs++;
} else if (secs < 0 && nanos > 0) {
secs--;
}
} catch (DateTimeException ex2) {
nanos = 0;
}
return ofSeconds(secs, nanos);
}
Then you have to call toHours() which then parses the created Duration object to return the hours as long
B) ChronoUnit.HOURS.between(begin, end);
Directly calls
long until(Temporal endExclusive, TemporalUnit unit);
//But instead of the implementation before, now it is called with unit of HOURS directly
which directly returns the hours as long.
Comparison of implementations
Both work the same way (for Hours at least) and give the same result.
But for A it seems we have some back and forth conversions which are not necessary.
Solution B seems straight forward without any conversions that we don't need
Answer
I would chose B as more efficient
It seems that both methods finally call Temporal#until
Duration#between
\
Temporal#until (used twice but some branching go for another implementation)
ChronoUnit.HOURS#between
\
Temporal#until (it is the only method underlying)