如何在java中解析不可解析的日期

时间:2015-09-15 09:39:42

标签: java date

我在一个应用程序中工作,我必须在控制器中发送一些日期,但如果我发送日期为空白,它将获得无法预料的日期例外,日期选择器我的日期格式为2015-09-02,并且我正在做的控制器

java.text.DateFormat outputFormat1 =new java.text.SimpleDateFormat("yyyy-MM-dd");
java.text.DateFormat outputFormat2 =new java.text.SimpleDateFormat("dd MMMM yyyy");
interviewPhoneorOnsiteDate = outputFormat2.format(outputFormat1.parse(interviewDate));

此代码我用于根据我的格式解析日期

以及我获取日期的方式是

String interviewDate = ParamUtil.getString(uploadRequest, "start-date");    

但是当日期字段为空时,发生异常,请任何人帮忙

这是例外

Caused by: java.text.ParseException: Unparseable date: ""
at java.text.DateFormat.parse(Unknown Source)
at com.msh.InterviewScheduleController.insertCandidateDetails(InterviewScheduleController.java:502)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.liferay.portal.kernel.portlet.LiferayPortlet.callActionMethod(LiferayPortlet.java:148)
... 134 more

实际问题在于此行

    Date interviewDateAdded = formatter.parse(dateInString); 

当它为null时,它无法解析

1 个答案:

答案 0 :(得分:0)

使用DateFormat.parse()引发的ParseException,如API

所示
  

ParseException - 如果无法解析指定字符串的开头。

try {    
    java.text.DateFormat outputFormat1 =new java.text.SimpleDateFormat("yyyy-MM-dd");
    java.text.DateFormat outputFormat2 =new java.text.SimpleDateFormat("dd MMMM yyyy");
    interviewPhoneorOnsiteDate = outputFormat2.format(outputFormat1.parse(interviewDate));
} catch (ParseException ex) {
     // do action if date cannot be parsed
     // return error unvalid date or what you need
}