2015-09-15 45 views
-4

我正在一个应用程序中工作,我必须在控制器中发送一些日期,但是如果我发送日期空白,它将获得不可解析的日期异常,那么日期选择器中的日期格式为2015 -09-02,并在控制器我做如何在java中解析无法解析的日期

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

当它是空它可以不解析

+2

'如果(interviewDate.equals( “”)){...}'或者类似的东西?另一个想法是'try {...} catch(...){...}'。请展示自我研究的最小努力。 –

+2

你为什么不使用try/catch? – vincent

+0

嗯但是我要问的是什么问题 – lucifer

回答

0

只用ParseException抛出DateFormat.parse()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 
} 
+0

我已经添加了这个异常,请参阅 – lucifer

+0

这正是我的代码所做的,捕获ParseException,如果日期不能被解析,默认情况下只给'interviewPhoneorOnsiteDate'值。 –

+0

我必须vilidate窗体的日期不能为空,所以我不能给予默认的格式,如果日期是空白的,我必须运行一些味精,那为什么我检查 – lucifer