Carter
Carter

Reputation: 57

Use SimpleDateFormat to validate a date

I want to create a method to validate a date by using SimpleDateFormat.

If the date is valid(e.g. 02/09/2012 or 2/09/2012 or 02/9/2012), this method should return true.

But if the format of the date is wrong(e.g. 02/09/201X) or logically wrong(e.g. 32/09/2012), this method should return false.

I try to write this method like this:

private boolean isValidDate(String date) {
        DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
        DateFormat df2 = new SimpleDateFormat("d-MM-yyyy");
        DateFormat df3 = new SimpleDateFormat("dd-M-yyyy");
        Date d = null;
        String s = null;

        try {
            d = df1.parse(date);
        }catch (Exception e1) {
            try{
                d = df2.parse(date);
            }catch (Exception e2) {
                try {
                    d= df3.parse(date);
                }catch (Exception e3) {
                    return false;
                }
                s = df3.format(d);
                return date.equals(s);
            }
            s = df2.format(d);
            return date.equals(s);
        }
        s = df1.format(d);
        return date.equals(s);
    }

But if I validate a date, for instance, 2/09/2012, it returns false (actually it should return true). I have no idea why... Can anyone find what's the problem with my code, or this logic is totally wrong? Is there any better way to do this validation?

Upvotes: 0

Views: 5349

Answers (4)

GregC
GregC

Reputation: 19

Add this additional check after parsing each string:

  1. Tokenize the value of the date String
  2. Then use the extracted day, month and year values to create a new Date object using GregorianCalendar
  3. Compare this to the date object you created from parsing the date strings
  4. If they match then you know that the input string contained a valid date format

Upvotes: 0

Janoz
Janoz

Reputation: 953

The validation fails because / isn't -.

Upvotes: 1

rolve
rolve

Reputation: 10218

I think your code is fine (but not very scalable - try to do it in a for-loop in case you add more formats later).

The problem is that your format strings are wrong. Instead of dd-MM-yyyy you should have dd/MM/yyyy. The same goes for the rest of the formats:

DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
DateFormat df2 = new SimpleDateFormat("d/MM/yyyy");
DateFormat df3 = new SimpleDateFormat("dd/M/yyyy");

Upvotes: 1

kosa
kosa

Reputation: 66637

Your input is in the format 2/09/2012 not 2-09-2012, so your dateformat should be like below:

    DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
    DateFormat df2 = new SimpleDateFormat("d/MM/yyyy");
    DateFormat df3 = new SimpleDateFormat("dd/M/yyyy");

Upvotes: 2

Related Questions