Debopam Mitra
Debopam Mitra

Reputation: 1870

SimpleDateFormat and Date Comparison not given correct ouput

try {
            Date sysDate = new SimpleDateFormat("dd/mm/yyyy").parse(_sysDate);
            Date userDate = new SimpleDateFormat("dd/mm/yyyy").parse(_userDate);
            if (userDate.compareTo(sysDate) > 0)
                return false;
                    else 
                            return true;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Above is my following code snippet to check two dates which is greater or not. When I am giving : sysdate=12/9/2012 and userdate=11/9/2012 or 10/8/2012 or 15/9/2011 it is giving the correct output

But when I am giving : sysdate=12/9/2012 and userdate=13/8/2012 or 15/7/2012 or 16/6/2012 it is giving incorrect output. To my analysis I have come to this point if I choose any month between Jan' 12 to Aug '12 and select the day_of_month(i.e. 0,1,2,...,31) more than the current day_of_month (in this case 12), I always get an incorrect output.

Please suggest any possible solution.

Upvotes: 0

Views: 1281

Answers (3)

NagarjunaReddy
NagarjunaReddy

Reputation: 8645

see this data format change like this dd/MM/yyyy in place of dd/mm/yyyy.

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Upvotes: -3

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

The problem is the pattern which should be "dd/MM/yyyy" (with capital "MM" for month) instead of "dd/mm/yyyy" (with small "mm" which means minutes).

So, it should be as follows -

try {
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date sysDate = df.parse(_sysDate);  
    Date userDate = df.parse(_userDate);
    //... 

Upvotes: 4

Ami
Ami

Reputation: 4259

try {
            Date sysDate = new SimpleDateFormat("dd/MM/yyyy").parse(_sysDate);
            Date userDate = new SimpleDateFormat("dd/MM/yyyy").parse(_userDate);
            if (userDate.compareTo(sysDate) > 0)
                return false;
                    else 
                            return true;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

The Date pattern is wrong dd/MM/yyyy instead of dd/mm/yyyy.

Upvotes: 1

Related Questions