0

I am facing issue related to date format pattern. Suppose user gives wrong input like this '200000-05-16' and I have format like this mm/dd/yyyy. I want to check format in java class the input date is wrong.

How is it possible to do in java?

Vitalii Elenhaupt
  • 7,146
  • 3
  • 27
  • 43
Sitansu
  • 3,225
  • 8
  • 34
  • 61

3 Answers3

7

Here is two solutions. I recommend the second one (the mkyong tutorial).

Solution 1 (Regexp)

String datePattern = "\\d{2}-\\d{2}-\\d{4}";

String date1 = "200000-05-16";
String date2 = "05-16-2000";

Boolean isDate1 = date1.matches(datePattern);
Boolean isDate2 = date2.matches(datePattern);

System.out.println(isDate1);
System.out.println(isDate2);

Output :

false
true

The pattern is not the better one because you could pass "99" as a month or a day and it will be ok. Please check this post for a good pattern : Regex to validate date format dd/mm/yyyy

Solution 2 (SimpleDateFormat)

This solution take a SimpleDateFormat to check if it is valid or not. Please check this link for a complete and great solution : http://www.mkyong.com/java/how-to-check-if-date-is-valid-in-java/

Community
  • 1
  • 1
romfret
  • 391
  • 2
  • 11
3
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class TestDate {

    public static boolean isValid(String value) {
        try {
            new SimpleDateFormat("dd/mm/yyyy").parse(value);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }
}
Hung Tran
  • 133
  • 1
  • 6
1

Try to parse it, if it fails - the format was not correct.

Keep in mind that SimpleDateFormat is not thread safe, so do not reuse the instance from several Threads.

folkol
  • 4,752
  • 22
  • 25