Java 如何在 JSTL 中使用格式日期为“yyyy-MM-dd”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22824190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use format date as "yyyy-MM-dd" with JSTL?
提问by nazar_art
I want to take date from DB and display on jsp:
我想从数据库中获取日期并在 jsp 上显示:
2014-04-02
2014-04-02
instead of:
代替:
2014-04-02 00:00:00.0
2014-04-02 00:00:00.0
On jsp I tried to use c:fmttag for formatting date:
在 jsp 上,我尝试使用c:fmt标记格式化日期:
<div class="form-group">
<span><fmt:message key="task.start"/></span>
<input class="form-control" id="firstDate" placeholder="<fmt:message key="task.start"/>"
name="start_date-${task.taskId}"
<fmt:formatDate value="${task.startDate}" var="startFormat" type="date" pattern="yyyy-MM-dd"/>
value="${startFormat}"/>
</div>
Looking on the page:
在页面上查看:
How to format it to yyyy-MM-ddformat?
如何将其格式化为yyyy-MM-dd格式?
采纳答案by tiny4penguin
First you need to add the line below to head of your jsp file
首先,您需要将以下行添加到您的 jsp 文件的头部
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
Now you can use <fmt:formatDate>
and <fmt:parseDate>
for formatting date.
现在您可以使用<fmt:formatDate>
和<fmt:parseDate>
格式化日期。
<fmt:formatDate value="${now}" pattern="yy-MMM-dd"/>
PS: In your code, I saw you had some mistakes with the jsp tag. I think it should be
PS:在你的代码中,我看到你的jsp标签有一些错误。我认为应该是
<div class="form-group">
<span><fmt:message key="task.start"/></span>
<input class="form-control" id="firstDate" placeholder="<fmt:message key='task.start'/>"
name="start_date-${task.taskId}" value="<fmt:formatDate value='${task.startDate}' var='startFormat' type='date' pattern='yyyy-MM-dd'/>"
</div>
回答by Simon Arsenault
The value
for fmt:formatDate
is suppose to be a Date object (java.util.Date
). If the task.startDate
is a date as a String, then you need to convert it beforehand.
在value
为fmt:formatDate
是假设是Date对象(java.util.Date
)。如果task.startDate
是字符串形式的日期,则需要事先将其转换。
<fmt:parseDate value="${task.startDate}" pattern="yyyy-MM-dd HH:mm:ss" var="myDate"/>
<fmt:formatDate value="${myDate}" var="startFormat" pattern="yyyy-MM-dd"/>