Marisaluht Marisaluht - 4 months ago 20
Java Question

StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception java.lang.IllegalArgumentException: Cannot format given Object as a Date

I am getting exception in my java jsp servlet code I am getting the error mentioned in the title.

I tried the solution from the link already from stackoverflow which is mentioned below but no use..

My problem is null value is entered into the mysql database..I am stuck in it for two days already..

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


Error logs:

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)

Answer

Change:

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

to:

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