Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fmt:formatDate not working as expected

Tags:

jsp

jstl

I am trying to format a java.util.Date object, that I am getting in my jsp, into a pattern of "yyyy-MM-dd hh:mm:ss" but it still prints it in a different (default probably) format.

I have included the taglibrary using this statement -

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

and I am printing this as a value in a cell of a table using the following code line -

<td><fmt:formatDate pattern="yyyy-MM-dd hh:mm:ss" value="${proposal.creationDate}"/></td>

But it still prints as the following -

Wed May 24 00:00:00 IST 3911

Can someone please suggest, what I might be doing wrong.

like image 664
kshtjsnghl Avatar asked May 31 '11 13:05

kshtjsnghl


2 Answers

I had this same problem. I was able to fix it by setting a locale before attempting to format the date:

<fmt:setLocale value="en_US" />
<fmt:formatDate value="${now}" pattern="yyyy-MM-dd" />

This fixed the problem, but I don't know why.

like image 76
evil otto Avatar answered Sep 19 '22 13:09

evil otto


That will happen when the ${proposal.creationDate} actually returns a String instead of a fullworthy Date. Fix it accordingly.

private Date creationDate;

public Date getCreationDate() {
    return creationDate;
}

If you really can't change the type for some unobvious reason, then you need to parse it first by <fmt:parseDate>.

<fmt:parseDate var="realCreationDate" value="${proposal.creationDate}" pattern="EEE MMM dd HH:mm:ss z yyyy" locale="en" />
<fmt:formatDate value="${realCreationDate}" pattern="yyyy-MM-dd HH:mm:ss" />

But that's plain hacky.


Unrelated to the problem, hours are to be represented by HH not hh. See also SimpleDateFormat javadoc. The year 3911 instead of 2011 in the printout also suggests that you've used the deprecated Date constructor/methods to create it.

like image 24
BalusC Avatar answered Sep 18 '22 13:09

BalusC