Search code examples
javacompareto

How to compare two dates without the use of objects?


/** Reports whether or not date1 comes earlier in time than date2. For example, isEarlierThan("12-01-2015", "02-15-2017") is true but isEarlierThan("10-11-2016", "10-11-2016") and isEarlierThan("09-09-1967", "02-15-1933")is false. * /

public static boolean isEarlierThan (String date1, String date2) 

{
    if(date1.compareTo(date2) > 0) {
        return true;
    }
    else if (date1.compareTo(date2) <= 0) {
        return false;
    }
    else {
        return true;
    }
}

This code works sometimes but no always. I have ran a tests case and it fails. The following test case is below.

public void testIsEarlierThan () 
{
    assertTrue(isEarlierThan("12-01-2015", "02-15-2017"));
    assertFalse(isEarlierThan("10-11-2016", "10-11-2016"));
    assertFalse(isEarlierThan("09-09-1967", "02-15-1933"));
    assertTrue(isEarlierThan("02-14-2017", "02-15-2017"));
}

When I run the test case, only the first two work then it stops at the third one. But I don't understand whats wrong? if the first one works shouldn't the third one work just fine? Thanks in advance!


Solution

  • Answering my own question. And for future reference if anyone has a similar question.

    public static boolean isEarlierThan (String date1, String date2)
    {
    
        String month1 = date1.substring(0, 2);
        String month2 = date2.substring(0, 2);
    
        String day1 = date1.substring(3, 5);
        String day2 = date2.substring(3, 5);
    
        String year1 = date1.substring(6, 10);
        String year2 = date2.substring(6, 10);
    
        date1 = year1 + month1 + day1; // + month1 + day1
        date2 = year2 + month2 + day2; // + month2 + day2
    
        if (date1.compareTo(date2) < 0)
        {
            return true;
        }
        else if (date1.compareTo(date2) > 0)
        {
            return false;
        }
        else
        {
            return false;
        }
    }
    

    Basically I have a method that takes the two dates, takes them apart into a year, a month, and a day. Then puts them back together in a different order so that when I compare them it will print the which true if date1 is before date2 or false if date1 is after or equal to date2.