问题描述
- 格式转换问题date 麻烦大家解释的详细一点,应该怎么改才能没错误 !
- 这是错误提示:
HTTP Status 500 - java.lang.IllegalArgumentException: Cannot format given Object as a Datetype Exception report
message java.lang.IllegalArgumentException: Cannot format given Object as a Date
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.IllegalArgumentException: Cannot format given Object as a Date
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
lvjianyu.blog.HomeServlet.doGet(HomeServlet.java:30)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root causejava.lang.IllegalArgumentException: Cannot format given Object as a Date
java.text.DateFormat.format(DateFormat.java:281)
java.text.Format.format(Format.java:140)
org.apache.jsp.main_jsp._jspService(main_jsp.java:90)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
lvjianyu.blog.HomeServlet.doGet(HomeServlet.java:30)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
解决方案
这是错误代码
for(int i=0;i<list.size();i++){
Blog blog=(Blog)list.get(i);
SimpleDateFormat sdf=new SimpleDateFormat(""yyyy-MM-dd""); String date=sdf.format(blog.getCreatedTime()); sdf=new SimpleDateFormat(""HH:mm:ss""); String time=sdf.format(blog.getCreatedTime()); 应该怎么改?
解决方案二:
请参考如下代码:
public class DateDemo05{ public static void main(String args[]){ String strDate = ""2008-10-19 10:11:30.345"" ; // 准备第一个模板,从字符串中提取出日期数字 String pat1 = ""yyyy-MM-dd HH:mm:ss.SSS"" ; // 准备第二个模板,将提取后的日期数字变为指定的格式 String pat2 = ""yyyy年MM月dd日 HH时mm分ss秒SSS毫秒"" ; SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ; // 实例化模板对象 SimpleDateFormat sdf2 = new SimpleDateFormat(pat2) ; // 实例化模板对象 Date d = null ; try{ d = sdf1.parse(strDate) ; // 将给定的字符串中的日期提取出来 }catch(Exception e){ // 如果提供的字符串格式有错误,则进行异常处理 e.printStackTrace() ; // 打印异常信息 } System.out.println(sdf2.format(d)) ; // 将日期变为新的格式 }};
解决方案三:
用两个格式类型变量,分别来操作。然后转换
解决方案四:
String date = given.toString(); if (StringUtils.isNotBlank(date)) { if(date.length() < 11){ date += "" 00:00:00""; } return java.sql.Date.valueOf(date) }