Android 日期格式解析抛出未处理的异常
Android date format parse throwing an Unhandled Exception
我将日期作为单个 string
存储在数据库中,格式为“2 15 2015”(大概是 "M d yyyy"?)。下面代码中的 strDate
包含获取日期的方法的 return 值。我想解析日期以设置 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);
嗯,你确实有。只需用 try/catch 包围它,因为编译器会提示您。
您收到此编译时错误是因为您没有处理 parse
方法抛出的 ParseException
。这是必要的,因为 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
}
我将日期作为单个 string
存储在数据库中,格式为“2 15 2015”(大概是 "M d yyyy"?)。下面代码中的 strDate
包含获取日期的方法的 return 值。我想解析日期以设置 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);
嗯,你确实有。只需用 try/catch 包围它,因为编译器会提示您。
您收到此编译时错误是因为您没有处理 parse
方法抛出的 ParseException
。这是必要的,因为 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
}