Search code examples
javaif-statementjava-timedayofweeklocaldate

Java - Get the first Thursday of the month


I'm trying to get the first Thursday of the month

dates.forEach(date -> {
        System.out.println("Date: " + date);
        LocalDate dateT = date.with(firstInMonth(DayOfWeek.THURSDAY));
        System.out.println("First Thursday: " + dateT);
        if(date == dateT) {
            System.out.println("Date: " + date + " is the first thursday");
        }
        System.out.println("");
    });

dates is a hashset of LocalDate objects, 7 days for mon - sun They objects may be across two months (31st May, 1st June etc.)

The output of the prints is as expected, but the if is never triggered. I have the exact sae code running for the first Tuesday which runs fine.

It successfully picks up that the first Thursday of June is 2021-06-03, but the print in the if never triggers

Date: 2021-05-31
First Thursday: 2021-05-06

Date: 2021-06-06
First Thursday: 2021-06-03

Date: 2021-06-05
First Thursday: 2021-06-03

Date: 2021-06-04
First Thursday: 2021-06-03

Date: 2021-06-03
First Thursday: 2021-06-03

Date: 2021-06-02
First Thursday: 2021-06-03

Date: 2021-06-01
First Thursday: 2021-06-03

Solution

  • You are trying to compare two objects and not the values they are holding.

    For LocalDates specifically you can use isEqual

    dates.forEach(date -> {
            System.out.println("Date: " + date);
            LocalDate dateT = date.with(firstInMonth(DayOfWeek.THURSDAY));
            System.out.println("First Thursday: " + dateT);
            if(date.isEqual(dateT)) {
                System.out.println("Date: " + date + " is the first thursday");
            }
            System.out.println("");
        });