kshtjsnghl
kshtjsnghl

Reputation: 601

fmt:formatDate not working as expected

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.

Upvotes: 7

Views: 13830

Answers (2)

evil otto
evil otto

Reputation: 10582

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.

Upvotes: 16

BalusC
BalusC

Reputation: 1109695

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.

Upvotes: 1

Related Questions