<%@ attribute name="timestamp" requ...">

JSTL - use formatDate with java.sql.Timestamp

I have a tag with the following:

<%@ tag body-content="empty"%> <%@ attribute name="timestamp" required="true" type="java.sql.Timestamp"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <jsp:useBean id="dateValue" class="java.util.Date" /> <c:if test="${not empty timestamp}"> <jsp:setProperty name="dateValue" property="time" value="${timestamp}" /> <span title="${timestamp}"> <fmt:formatDate value="${dateValue}" pattern="MM/dd/yyyy HH:mm" /> </span> </c:if> 

I get the following error:

Error 500: com.ibm.ws.jsp.JspCoreException: java.lang.IllegalArgumentException: cannot convert 5/1/12 10:36 AM class of type java.sql.Timestamp to long

I tried to execute this answer to convert a timestamp to a date in JSTL so that I would not change anything in my servlet. How to convert java.sql.Timestamp to a date so that formatDate can work with it using JSTL?

+7
source share
1 answer

You need to go to Timestamp#getTime() .

 <jsp:setProperty name="dateValue" property="time" value="${timestamp.time}" /> 

But that makes no sense. java.sql.Timestamp already a subclass of java.util.Date . So this should also do:

 <%@ attribute name="timestamp" required="true" type="java.sql.Timestamp"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <c:if test="${not empty timestamp}"> <span title="${timestamp}"><fmt:formatDate value="${timestamp}" pattern="MM/dd/yyyy HH:mm" /></span> </c:if> 

By the way, I would also modify your models to declare the property as java.util.Date . You should not use java.sql.Timestamp in the model and view, but only in the data layer. You do not need to convert ResultSet#getTimestamp() to java.util.Date by parsing / formatting. A simple boost is enough.

eg.

 import java.util.Date; public class SomeModel { private Date somefield; // ... } 

from

 someModel.setSomefield(resultSet.getTimestamp("somefield")); 
+9
source

All Articles