我的java jsp servlet代码中出现异常,标题中提到了错误。
我已经从下面提到的stackoverflow链接中尝试了解决方案,但是没有用。

我的问题是将空值输入到mysql数据库中。我已经在其中停留了两天。

Java : Cannot format given Object as a Date

 import java.sql.Timestamp;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.time.Instant;
 import java.util.Date;
 import java.util.logging.Level;
 import java.util.logging.Logger;

 public class SetDate
 {
 public static java.util.Date set(String s,String f)
 {
 java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat(f);
 java.util.Date date=null;
 try
 {
 date=sdf.parse(s);
 }
 catch (ParseException ex)
 {
 Logger.getLogger(SetDate.class.getName()).log(Level.SEVERE, null, ex);
 }
 return date;
 }


public static String format(Object time,String f) throws ParseException
{
    SimpleDateFormat sdf=new SimpleDateFormat(f);
    System.out.println("Date:- " +sdf.format(time));
    return sdf.format(time);
}
}


错误日志:

Warning:   StandardWrapperValve[jsp]: Servlet.service() for servlet jsp   threw exception
java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(DateFormat.java:310)
at java.text.Format.format(Format.java:157)
at myweb.tool.SetDate.format(SetDate.java:35)

最佳答案

更改:

public static String format(Object time,String f) throws ParseException
{
    SimpleDateFormat sdf=new SimpleDateFormat(f);
    System.out.println("Date:- " +sdf.format(time));
    return sdf.format(time);
}


至:

public static String format(Object time,String f) throws ParseException
{
    if (time == null)
        rteurn null;

    SimpleDateFormat sdf=new SimpleDateFormat(f);
    System.out.println("Date:- " +sdf.format(time));
    return sdf.format(time);
}

09-20 23:04