1

I need to compare the two dates and know whether they are equal or < or >

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class App 
{
     public static void main( String[] args ) 
    {
        try{

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = sdf.parse("2009-12-31");
            Date date2 = sdf.parse("2010-01-31");

            System.out.println(sdf.format(date1));
            System.out.println(sdf.format(date2));

            if(date1.compareTo(date2)>0){
                System.out.println("Date1 is after Date2");
            }else if(date1.compareTo(date2)<0){
                System.out.println("Date1 is before Date2");
            }else if(date1.compareTo(date2)==0){
                System.out.println("Date1 is equal to Date2");
            }else{
                System.out.println("How to get here?");
            }

        }catch(ParseException ex){
            ex.printStackTrace();
        }
    }
}

the above Code doesnt work properly.. I tried this format MM-dd-YYYYit is checking oly if the year is > than the first date it gives >. Eg: i compared in this way d1 = 01-07-2014 d2 = 01-06-2014.. result should be d1 >d2 but it tells d1 is equal to d2

Kindly help me

Alex Michael Raj
  • 185
  • 2
  • 9
  • 24

3 Answers3

2

java.util.Date has a before and after method for exactly your purpose.

hd1
  • 33,938
  • 5
  • 80
  • 91
0

Add this instead of your code.This is the best way to compare Date in Java.

    if(date1.after(date2)){
        System.out.println("Date1 is after Date2");
    }else if(date1.before(date2)){
        System.out.println("Date1 is before Date2");
    }else {
        System.out.println("Date1 is equal to Date2");
    }
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

The format you use is incorrect pattern to symbolize year is 'y' but not 'Y'. So pattern should be correct as "MM-dd-yyyy" instead "MM-dd-YYYY"

additionally you can do with local date the same,

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import org.junit.Test;

public class LocalDateTest {


    @Test
    public void compare_local_dates() throws Exception {

        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date1 = LocalDate.parse("2009-12-31", pattern);
        LocalDate date2 = LocalDate.parse("2010-01-31", pattern);

        System.out.println(pattern.format(date1));
        System.out.println(pattern.format(date2));


        if(date1.isAfter(date2)){
            System.out.println("Date1 is after Date2");
        }else if(date1.isBefore(date2)){
            System.out.println("Date1 is before Date2");
        }else if(date1. isEqual(date2)){
            System.out.println("Date1 is equal to Date2");
        }else{
            System.out.println("How to get here?");
        }


    }

}
asela38
  • 4,546
  • 6
  • 25
  • 31