1

I'm storing dates in a database as a single string in the format "2 15 2015" (presumably "M d yyyy"?). strDate in the code below contains the return value of a method that grabs the date. I want to parse the date so as to set a datepicker. Based on the examples in Java string to date conversion

I've created the following code for parsing the date, but am getting an "Unhandled Exception: java.text.ParseException" at

Date date = format.parse(strDate);

Scratching my head.

Calendar mydate = new GregorianCalendar();
String strDate = datasource.get_Column_StrVal(dbData,
        MySQLiteHelper.dbFields.COLUMN_SPECIAL_DAYS_DATE);
SimpleDateFormat  format = new SimpleDateFormat("M d yyyy", Locale.ENGLISH);
Date date = format.parse(strDate);
mydate.setTime(date);
Community
  • 1
  • 1
E. A. Bagby
  • 824
  • 9
  • 24

2 Answers2

3

You are getting this compile-time error because you are not handling the ParseException that the parse method throws. This is necessary because ParseException is not a runtime exception (it is a checked exception since it extends directly from java.lang.Exception).

You need to surround your code with try/catch to handle the exception, like this :

try {
    SimpleDateFormat  format = new SimpleDateFormat("M d yyyy", Locale.ENGLISH);
    Date date = format.parse(strDate);
    mydate.setTime(date);
} catch (ParseException e) {
    //handle exception
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • That worked. It seems odd that the try catch is required. Do you recommend anything in the "//handle exception" line? – E. A. Bagby Feb 15 '15 at 18:25
  • 1
    `ParseException` is a checked exception. You either need to catch it or declare that your method can throw it (using `throws` clause). Handling the exception should answer the question "what should I do if a date is incorrect in DB ?". You probably need to log it at least. – Tunaki Feb 15 '15 at 18:30
1

Well, you indeed have it. Just surround it with try/catch as the compiler will hint you.

Michał Szydłowski
  • 3,261
  • 5
  • 33
  • 55