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

痞子三分冷 提交于 2019-12-11 16:44:31

问题


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.


回答1:


<%@ 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.




回答2:


You will need to use java.text.SimpleDateFormat class or Joda time.




回答3:


Use ..

DateFormat f = new SimpleDateFormat("yyyy-MM-dd"); .




回答4:


Use DateFormat

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat();
df.applyPattern("MM/dd/yyyy");
System.out.println(df.format(date));


来源:https://stackoverflow.com/questions/8193617/how-to-convert-java-util-date-to-required-format-in-scriptlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!