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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:08:26  来源:igfitidea点击:

How to use format date as "yyyy-MM-dd" with JSTL?

javajspdatejstl

提问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:

在页面上查看:

view

看法

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 valuefor fmt:formatDateis suppose to be a Date object (java.util.Date). If the task.startDateis a date as a String, then you need to convert it beforehand.

valuefmt: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"/>