JSTL - use formatDate with a java.sql.Timestamp

Sarah Vessels picture Sarah Vessels · May 2, 2012 · Viewed 9.2k times · Source

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 however:

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

I was trying to follow this answer to convert a timestamp to a date in JSTL, so I wouldn't have change anything in my servlet. How can I convert a java.sql.Timestamp to a date so that formatDate can work with it, using JSTL?

Answer

BalusC picture BalusC · May 2, 2012

You need to pass in Timestamp#getTime().

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

But this makes all no sense. The java.sql.Timestamp is 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>

I'd by the way also change your models to declare the property as java.util.Date instead. You should not use java.sql.Timestamp in the model and view, but only in the data layer. You don't need to convert ResultSet#getTimestamp() to java.util.Date by parsing/formatting. Just upcasting is sufficient.

E.g.

import java.util.Date;

public class SomeModel {

    private Date somefield;

    // ...
}

with

someModel.setSomefield(resultSet.getTimestamp("somefield"));