16

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:

view

How to format it to yyyy-MM-dd format?

user2418306
  • 2,352
  • 1
  • 22
  • 33
catch23
  • 17,519
  • 42
  • 144
  • 217
  • related http://stackoverflow.com/questions/2620676/how-to-format-date-in-jstl – Adriano Sep 04 '14 at 09:12
  • relevant doc http://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/fmt/tld-summary.html and also http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html – Adriano Sep 04 '14 at 09:13

2 Answers2

28

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>
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
tiny4penguin
  • 311
  • 2
  • 4
13

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"/>
Simon Arsenault
  • 1,241
  • 11
  • 12