7

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?

Community
  • 1
  • 1
Sarah Vessels
  • 30,930
  • 33
  • 155
  • 222

1 Answers1

9

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"));
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Oh, derp. I never tried just using `formatDate` directly on the timestamp, since I saw questions online about having to convert a timestamp to a date to use it with `formatDate`. Thanks! – Sarah Vessels May 02 '12 at 15:46
  • Other questions were talking about timestamp as in a `long` value indicating the epoch time. But you actually already have a `java.sql.Timestamp` which in turn is thus already a subclass of `java.util.Date`. – BalusC May 02 '12 at 15:48