0

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.

4

2 回答 2

2

对于大多数情况,您需要java.util.Date而不是java.sql.Date

文档_java.sql.Date

抛出:IllegalArgumentException - 如果给定的日期不是 JDBC 日期转义格式 (yyyy-mm-dd)

这意味着来自 jsp 的日期不是格式的yyyy-mm-dd形式。

如果要使用 java.sql.Date 对象,则yyyy-mm-dd在使用valueOfAPI 之前将传入的日期格式化为格式化。

对于转换,您可以使用SimpleDateFormat将传入值格式化为yyyy-mm-dd.

编辑:

最好不要使用 Date 对象,而是应该使用Calendar进行大部分操作。

编辑:

根据评论:

假设我来自 JSP 的传入日期是 dd-MMM-yyyy 格式。

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();
    }
}
于 2012-04-25T09:24:24.130 回答
0

使用 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);
    }
}
于 2012-04-25T09:26:28.847 回答