-2

I have a constructor that takes a Date input in this format "Nov 15 2015" then i use below method to convert it to an SQL date format. When i read from the DB I convert it back to java.util.Date to be stored in the bean.

public static java.sql.Date inDate(String Date) {
    String startDateInput = Date;
    try {
        // Start Date
        String sDate = new SimpleDateFormat("yyyy-MM-dd")
            .format(new SimpleDateFormat("MMM dd yyyy").parse(startDateInput));
        java.sql.Date starDate = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse(sDate).getTime());
        return starDate;
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

My Question is how can i check if the date was entered in this format "Nov 15 2015" and if not throw an exception?

Smern
  • 18,746
  • 21
  • 72
  • 90
aronowt
  • 9
  • 1
  • 6
  • 1. Format the resulting sDate value with the same as the Date value; 2. Don't do this anyway. Instead use a java.sql.Date or java.sql.Timestamp to bind the value to your queries through PreparedStatements – MadProgrammer Nov 03 '15 at 19:42
  • 1
    You already catch a `ParseException` which let's you know if `Date` was malformed, what else do you want? – Tom Nov 03 '15 at 20:35

1 Answers1

0

let me try to answer this.

  1. Do not use 'Date' as a name for a variable (it's reserved for java) and do not start variables with capital letters.

  2. you can us regular expression before you go ahead with your string. (check this to find your regex patterns: Regular Expression to match valid dates)

Community
  • 1
  • 1