dkea
dkea

Reputation: 708

How to set DATE in object, JSP SERVLET

I've had this time for about quite sometime now and i've run out of resources for research.

In my servlet, i have this code:

    comment.setDateadded(Date.valueOf(request.getParameter("date")));

The code basically gets data from a JSP page then is set as one of the object's values.

The problem is:

When the servlet is called and run returns this error:

WARNING: StandardWrapperValve[add_comment]: PWC1406: Servlet.service() for servlet add_comment threw exception
java.lang.IllegalArgumentException
    at java.sql.Date.valueOf(Date.java:117)
    at Controller.Leader.add_comment.processRequest(add_comment.java:50)
    at Controller.Leader.add_comment.doPost(add_comment.java:96)

What i've tried: I'm not sure what the problem is anymore. I imported

import java.sql.Date; 

in the servlet ofor the line to work. I've also tried manually putting in the date instead of putting automatically the current date but it still does not work. Ive tried yyyy/mm/dd format and the yyyy-mm-dd but it still wont work.

For those who will comment, thank you very much! If you need more details, please post.

Upvotes: 0

Views: 6686

Answers (2)

mprabhat
mprabhat

Reputation: 20323

For most of the scenario you need java.util.Date and not java.sql.Date

From the documentation of java.sql.Date

Throws: IllegalArgumentException - if the date given is not in the JDBC date escape format (yyyy-mm-dd)

which means date coming from jsp is not in the form of yyyy-mm-dd format.

If you are going to use java.sql.Date object then format the incoming date to yyyy-mm-dd format before using valueOf API.

For conversion you can use SimpleDateFormat to format your incoming value to yyyy-mm-dd.

Edit:

Even better instead of using Date object you should Calendar for most of the operation.

Edit:

As per comments:

Assuming my Incoming date from JSP is dd-MMM-yyyy format.

try {
    String date = "25-Apr-2012";
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    java.util.Date parsedDate = dateFormat.parse(date);
    dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    date = dateFormat.format(parsedDate);
    System.out.println(date);
    java.sql.Date sqlDate = java.sql.Date.valueOf(date);
    System.out.println(sqlDate);
    } catch (ParseException e) {
       e.printStackTrace();
    }
}

Upvotes: 2

Satya
Satya

Reputation: 8881

an example of using java.sql.Date

public class A
{
    public static void main(String [] args)
    {
        java.sql.Date jsqlD = java.sql.Date.valueOf( "2010-01-31" );    
        System.out.println(jsqlD);
    }
}

Upvotes: 0

Related Questions