javajava-time

Duration.between vs ChronoUnit.between


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?


Solution

  • Analyzed implementation on open JDK 15.


    A) Using Duration.between(begin, end).toHours()

    Duration.between(begin, end) first calls

    // called with unit of NANOS or SECONDS if first one fails
    long until(Temporal endExclusive, TemporalUnit unit);
    

    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) Using ChronoUnit.HOURS.between(begin, end)

    Directly calls

    // in this case it is called with unit of HOURS directly
    long until(Temporal endExclusive, TemporalUnit unit);
    

    which directly returns the hours as long.


    Comparison of implementations

    Answer

    I would chose the solution B) as more efficient.