Search code examples
javastringdatecomparecompareto

Comparing dates in Java


I already read date functions but i cant think a best way to solve my problem.

I have a couple of dates from database which is String and i want to compare it to may current date. I am using the compareTo, but there is a problem using this function i guess it is because of i was comparing strings.

This is my function:

public int dateCompare(String today, String date2){
    return today.compareTo(date2);
}

And when i use it in sample dates:

dateCompare("04/19/2013","04/18/2013");

it returns 1, and when i change the value of first parameter to "04/20/2013" it still returns 1.

Please HELP...


Solution

  • Java has a Date object. You should be using that instead.

    import java.util.Calendar;
    import java.util.Date;
    
    public class CompareDates {
    
        public static void main(String[] args) {
            // Create a calendar, this will default to today
            Calendar cal = Calendar.getInstance();
            // Subtract 1 day
            cal.add(Calendar.DATE, -1);
            // Compare the result (1)
            System.out.println(dateCompare(new Date(), cal.getTime()));
            // Add 2 days
            cal.add(Calendar.DATE, 2);
            // Compare the result (-1)
            System.out.println(dateCompare(new Date(), cal.getTime()));            
        }
    
        public static int dateCompare(Date today, Date date2) {
            System.out.println("Compare " + today + " with " + date2);
            return today.compareTo(date2);
        }
    }
    

    You could also just make use of the Date API and use before and after...

    Date now = new Date();
    
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -1);
    System.out.println(now + " isBefore " + cal.getTime() + " = " + now.before(cal.getTime()));
    System.out.println(now + " isAfter " + cal.getTime() + " = " + now.after(cal.getTime()));
    cal.add(Calendar.DATE, 2);
    System.out.println(now + " isBefore " + cal.getTime() + " = " + now.before(cal.getTime()));
    System.out.println(now + " isAfter " + cal.getTime() + " = " + now.after(cal.getTime()));