views:

539

answers:

2
+1  Q: 

JSTL - Format date

Hi! I have a loop that goes through all the news items we have on our site. One of the fields is date ${newsitem.value['Date']}, given in millliseconds. I'd like to display this date in month/day/year format on the webpage. I thought JSTL format tag, <fmt:formatDate>, would help, but I haven't succeeded. Do you know how to do it?

<cms:contentaccess var="newsitem" />
<h2><c:out value="${newsitem.value['Title']}" /></h2>
// display date here        
<c:out value="${newsitem.value['Text']}"  escapeXml="false" />
+1  A: 

Yes the JSTL formatDate tag should do the job in combination with changing the Timestamp value into a date object (which is required to work around the exception mentioned in your comment).

Ensure that you have properly defined the fmt prefix in the JSP declarations

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

Render the output, convert the time stamp to a date value first. I'm using yyyy-MM-dd as the format pattern, the dateFormat tag supports other formatting options as well.

<cms:contentaccess var="newsitem" />
<jsp:useBean id="newsDate" class="java.util.Date" />
<jsp:setProperty name="newsDate" property="time" value="${newsitem.value['Date']}" />
<h2><c:out value="${newsitem.value['Title']}" /></h2>
<fmt:formatDate pattern="yyyy-MM-dd" value="${newsDate}" />
<c:out value="${newsitem.value['Text']}" escapeXml="false" />
BenM
I've tried this earlier but it throws this error:"Cannot convert 1270738800000 of type class org.opencms.jsp.util.CmsJspContentAccessValueWrapper to class java.util.Date"
John Manak
The taglib URI indicates an 10 year old version of JSTL. Please upgrade.
BalusC
thanks for spotting the old URI, I've upgraded it as you've suggested
BenM
updated the answer to incorporate some of suggestions from BalusC and add additional links and information
BenM
+1  A: 

"Cannot convert 1270738800000 of type class org.opencms.jsp.util.CmsJspContentAccessValueWrapper to class java.util.Date"

This is pretty self-explaining. It's not a java.util.Date. It's something entirely different which has a string representation (Object#toString() of a timestamp). It's coming straight from OpenCMS. I have never used OpenCMS, so I don't know if there are OpenCMS specific solutions to this, but in theory you can just create a fullworthy java.util.Date based on the the timestamp using <jsp:useBean> and then format it the way you want.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
...
<jsp:useBean id="newsDate" class="java.util.Date" />
<jsp:setProperty name="newsDate" property="time" value="${newsitem.value['Date']}" />
...
<p>Date: <fmt:formatDate value="${newsDate}" type="date" dateStyle="long" /></p>
BalusC
Upvoted for a nice JSP-only solution to the timestamp to Date issue
BenM