0

I'm trying to compare two dates, both of which are already in String value, in the form of "2018-01-01". I would like to compare the dates based on the year and month, and if they are equal, I'd like to print out a result.

I have managed to print out a result when both dates are equal to one another in String form, but I acknowledge that I may have to convert the two Strings into a Date or LocalDate format. I've attempted a search to find an answer, but none really solve my issue and most refer to SQL, whereas I'm looking for a Java based solution.

String Date1 = "2018-01-01"
String Date2 = "2018-01-12"

 if(Date1.trim().equals(Date2.trim())){
 System.out.println("Both dates are equal to one another")
}

If the dates don't have an exact match, I want to instead compare the dates based on the year and month only. This would probably require parsing the String into a Date or LocalDate format. The problem is I don't exactly understand how to do that. I don't want to change the values inside the Strings either, so something like cal.setTime(); won't work as I want.

jayjay275
  • 65
  • 6

1 Answers1

3

YearMonth::equals

You could use YearMonth class from Java 8 and later:

public static void main(String[] args) {
        String date1 = "2018-02-04";
        String date2 = "2018-02-05";

        LocalDate localDate1 = LocalDate.parse(date1);
        LocalDate localDate2 = LocalDate.parse(date2);

        if(YearMonth.from(localDate1).equals(YearMonth.from(localDate2))) {
            System.out.println("Year and month are the same");
        }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63