1

I want to print out a result provided that the dates match, depending on either month or the specific day.

At the moment, I can only get it to print out a correct message if the dates fully match; the first date is generated from user input, so if that changes, I'd like to compare it to the second date to see if the year and month are still the same. If they are the same, I'd like to print out "Correct" as well.

String date1 = "2018-02-04";
String date2 = "2018-02-04";

if(date1.trim().equals(date2.trim())){
System.out.println("Correct");
}




ADDED/UPDATED FOR CLARIFICATION:

while (m.hasNextLine()) 
        {   
                carReg = m.next();
                carModel = m.next();
                carType = m.next();
                vehicleSize = m.next();
                carColour = m.next();
                carMileage = m.next();
                carAccidentHistory = m.next();
                carTransmissionType = x.next();
                carCost = m.next();
                DateArrived = m.next();
                DateSold = m.next();


                m.nextLine();



    if(userDate.trim().equals(DateSold.trim())){            

    System.out.println("Correct output.");
                }


// This if condition works fine, but I'm attempting to match the date the user inputs to any date that is being scanned, provided the year and month match. 


jayjay275
  • 65
  • 6
  • 1
    "only ... if the dates fully match" please define what a not-quite-full match looks like – Michael Apr 23 '19 at 13:24
  • 3
    If you're really interested in treating the values as *dates*, I'd start off by parsing them to `LocalDate` values. Everything else will be easier after that. – Jon Skeet Apr 23 '19 at 13:25
  • 1
    Will the user input always be in the yyyy-MM-dd format? – Sweeper Apr 23 '19 at 13:26
  • For a better solution, you could check [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion) (use the Java 8 update) then some answers in [How to compare dates in Java?](https://stackoverflow.com/questions/2592501/how-to-compare-dates-in-java) like [gstackoverflow](https://stackoverflow.com/a/33693122/4391450) short solution in Java 8 – AxelH Apr 23 '19 at 13:46
  • Please, take a look at my update @jayjay275 . Happy coding. – MS90 Apr 23 '19 at 14:28
  • @Michael A non-match would be something like: 2018-05-05 against 2019-05-05. I'm looking to match two strings based on either the same day in a year and month, or same month and year. – jayjay275 Apr 23 '19 at 14:29
  • @MS90 I updated it further to see if you know what I mean – jayjay275 Apr 23 '19 at 14:46
  • Take a look at updated answer. @jayjay275 – MS90 Apr 23 '19 at 15:14

3 Answers3

3

Why not just use LocalDate class for this :

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);

        boolean isSameYear = localDate1.getYear() == localDate2.getYear();
        boolean isSameMonth = localDate1.getMonthValue() == localDate2.getMonthValue();

        if(isSameYear && isSameMonth) {
            System.out.println("correct");
        }

    }

EDIT :

Thanks to @assylias we could simplify previous code to :

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("correct");
        }
    }
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
1

You could do the following using Java8. So parse your string to LocalDate instances and try calling methods for dates comparison isEqual, isAfter and isBefore for all three scenarios regarding dates comparisons.

String date1 = "2018-05-04";
String date2 = "2018-02-04";
//DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);

LocalDate localDate1 = LocalDate.parse(date1);

LocalDate localDate2 = LocalDate.parse(date2);//with formatter  LocalDate.parse(date2,formatter);

//System.out.println(localDate1.isEqual(localDate2) ? "Dates are equal." : localDate1.isAfter(localDate2) ? " Date1 is after Date2 " : " Date1 is before Date2 ");
if (localDate1.isAfter(localDate2)) {
    System.out.println("Date1 is after Date2");
}

else if (localDate1.isBefore(localDate2)) {
    System.out.println("Date1 is before Date2");
}

else {
    System.out.println("Date1 is equal Date2");
}

UPDATE 2: Based on your new request, to write out Correct if year and month are the same for given dates, you could do something like following:

boolean isSameYearAndMonth = localDate1.getLong(ChronoField.PROLEPTIC_MONTH) == localDate2.getLong(ChronoField.PROLEPTIC_MONTH);

This checks whether is the same number of months from year 0 for provided dates and if it is correct, return true, if not returns false, so simply checking it like following

if(isSameYearAndMonth)
{
   System.out.println("Correct");
}
else
{
   System.out.println("Not correct");
}

UPDATE 3 The easiest way for you in this occasion would be to have a flag in while loop which denotes whether two dates match in year and month, so something like that would make your way:

 //flag used for entering while loop
        boolean flag = true;
        //two simple variables for simple example
        String variable1, variable2;
        Scanner scanner = new Scanner(System.in);
        while (flag) {
            System.out.println("Enter variable1");
            variable1 = scanner.next();
            System.out.println("Enter date variable:");
            variable2 = scanner.next();

            boolean take = sameMonthSameYear(variable1, variable2);
            if(take)
            {
                //if we finally match two dates, exit while loop
                flag = false;
            }

        }

and use following method in your while loop

public static boolean sameMonthSameYear(String date1, String date2) {

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
    LocalDate localDate1 = LocalDate.parse(date1);
    LocalDate localDate2 = LocalDate.parse(date2);
    boolean isSameYearAndMonth = localDate1.getLong(ChronoField.PROLEPTIC_MONTH) == localDate2.getLong(ChronoField.PROLEPTIC_MONTH);
    if(isSameYearAndMonth)
    {
        System.out.println("correct");
    }
    else
    {
        System.out.println("not correct");
    }
    return isSameYearAndMonth;
}
MS90
  • 1,219
  • 1
  • 8
  • 17
  • 1
    You don't need a formatter in this case - the default formatter will work just fine. – assylias Apr 23 '19 at 13:41
  • You are completely right, however I tend to go step by step in order to show him what's going on. He might be wondering how did I turn it into LocalDate just like that. – MS90 Apr 23 '19 at 13:43
  • I probably should've explained it beforehand, but the second date is in a while loop, so that is constantly changing as well. Would this be easily adjusted by placing the localdate2 variable in the while loop in the correct place? – jayjay275 Apr 23 '19 at 14:31
  • OK, no problem, just edit your Q. and put a code example and I will put it into place. @jayjay275 – MS90 Apr 23 '19 at 14:33
0

You should use LocalDate as already commented/answered by others.

However if you want to stick with strings and assuming format of the input is always the same, you can use the String.substring(int beginIndex, int endIndex) method:

String date1 = "2018-02-04";
String date2 = "2018-02-07";

if(date1.substring(0, date1.lastIndexOf('-')).equals(date2.substring(0, date2.lastIndexOf('-')))){
    System.out.println("Correct");
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28