Android日期格式解析抛出未处理的异常

时间:2015-02-15 18:13:41

标签: java android date

我将日期作为单个string存储在数据库中,格式为“2 15 2015”(大概是“M d yyyy”?)。下面代码中的strDate包含获取日期的方法的返回值。我想解析日期以设置datepicker。基于Java string to date conversion

中的示例

我已经创建了以下用于解析日期的代码,但我在

处获得了“Unhandled Exception: java.text.ParseException
Date date = format.parse(strDate);

抓我的头。

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);

2 个答案:

答案 0 :(得分:2)

您收到此编译时错误,因为您没有处理ParseException方法抛出的parse。这是必要的,因为ParseException不是运行时异常(它是一个经过检查的异常,因为它直接从java.lang.Exception扩展。)

您需要使用try / catch包围代码来处理异常,如下所示:

try {
    SimpleDateFormat  format = new SimpleDateFormat("M d yyyy", Locale.ENGLISH);
    Date date = format.parse(strDate);
    mydate.setTime(date);
} catch (ParseException e) {
    //handle exception
}

答案 1 :(得分:1)

嗯,你确实拥有它。只需用try / catch包围它,因为编译器会暗示你。