How to use format date as “yyyy-MM-dd” with JSTL? [duplicate]

本秂侑毒 提交于 2019-12-22 03:38:07

问题


I want to take date from DB and display on jsp:

2014-04-02

instead of:

2014-04-02 00:00:00.0

On jsp I tried to use c:fmt tag for formatting date:

   <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-dd format?


回答1:


First you need to add the line below to head of your jsp file

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

    <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>



回答2:


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.

<fmt:parseDate value="${task.startDate}" pattern="yyyy-MM-dd HH:mm:ss" var="myDate"/>
<fmt:formatDate value="${myDate}" var="startFormat" pattern="yyyy-MM-dd"/>


来源:https://stackoverflow.com/questions/22824190/how-to-use-format-date-as-yyyy-mm-dd-with-jstl

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