Search code examples
javajspdatescriptlet

How to convert java.util.date to required format in scriptlet


I have a transfer object being returned to the JSP after a search. It is having a java.util.Date field (e.g. private Date issueDate;)

I am accessing the data in TO using usebean tag and displaying the date as:

<INPUT TYPE="text" readonly="readonly" NAME="issueDt" ID="issueDt" 
       SIZE="45" value="<%=mySearchTO.getIssueDt()%>">

However, this is printing the date in the format say for e.g. MON JAN 31 00:08:00 IST 2011

I want the date to be printed simply as MM/DD/YYYY and in the cases where time is also important, in the MM/DD/YYYY HH:MM format.

How to achieve this inside JSP? I don't know if I need to go for Javascript function or some static Java method.

Please excuse the usage of scriptlet. It's a legacy application and so I can not use EL. Please provide solution through scriptlet only. So solutions like:

<fmt:formatDate value="${new Date(c.dateInIntegerValue)}" 
                pattern="dd.MM.yyyy hh:mm"/> 

available in other questions, will not work for me.

Is the following code valid?

<fmt:formatDate value="<%=mySearchTO.getIssueDt()%>" 
                pattern="dd.MM.yyyy hh:mm"/> 

If yes, how to use it in the JSP? I mean label and all!

Also as far as possible, I want to avoid usage of jquery and such libraries.


Solution

  • <%@ page import="java.text.SimpleDateFormat" %>    
    <% SimpleDateFormat dateFormatWithTime = new SimpleDateFormat("MM/dd/yyyy hh:mm");%>
    <INPUT TYPE="text" readonly="readonly" NAME="issueDt" ID="issueDt" SIZE="45" value="<%=dateFormatWithTime.format(mySearchTO.getIssueDt())%>">
    

    Ideally you should just use formatDate from JSTL or factor out this code into a custom taglib.