javacomparetolocaldate

I don't understand LocalDate#compareTo() Java method return value


I'm trying to get skilled on dates using them with Java and the LocalDate class, there's something I don't understand about the compareTo method return value, though.

I thought that the nextDate.compareTo(previousDate) I'm using would return:

But i thought it was safe to say that the >0 return value and the <0 value were the span of time in terms of days, equals to nextDate - previousDate.

E.g. (yyyy-MM-dd):

According to the following tests, this is not always true and I don't understand why.

package com.mycompany.provalocaldatenuovo;

import java.time.LocalDate;

public class UI {

    public static void main(String args[]) {

        // Test 1
        LocalDate previousDate1 = LocalDate.of(2030, 01, 01);
        LocalDate nextDate1 = LocalDate.of(2030, 01, 31);

        // Test 2
        LocalDate previousDate2 = LocalDate.of(2030, 01, 01);
        LocalDate nextDate2 = LocalDate.of(2030, 01, 03);

        // Test 3
        LocalDate previousDate3 = LocalDate.of(2030, 01, 31);
        LocalDate nextDate3 = LocalDate.of(2030, 02, 03);

        // Test 4
        LocalDate previousDate4 = LocalDate.of(2030, 1, 31);
        LocalDate nextDate4 = LocalDate.of(2030, 1, 31);

        // Test 1 - expected 30
        System.out.println("TEST 1: " + nextDate1.compareTo(previousDate1));

        // Test 2 - expected 2
        System.out.println("TEST 2: " + nextDate2.compareTo(previousDate2));

        // Test 3 - expected 3
        System.out.println("TEST 3: " + nextDate3.compareTo(previousDate3));

        // Test 4 - expected 0
        System.out.println("TEST 4: " + nextDate4.compareTo(previousDate4));
    }
}

Output:

TEST 1: 30
TEST 2: 2
TEST 3: 1    //??? doesn't matter which day on february is, this will result 1
TEST 4: 0

Do you know what's going on TEST3?


Solution

  • At a guess, what is going on here is that it's returning:

    However, this isn't really important: the only thing you should be considering about the return value is its sign:

    The exact value itself (other than zero) is completely irrelevant, and subject to change if the internal implementation changes. You should only ever compare the result of compareTo (or compare) with zero, e.g. result < 0, result >= 0 etc.


    In the specific case of LocalDate (and other java.time classes), methods are provided to make the intent of the check more apparent:

    It's up to you (or your team style) as to which to prefer.