Taglib to display java.time.LocalDate formatted

Piotr Pradzynski picture Piotr Pradzynski · May 14, 2015 · Viewed 8.1k times · Source

I would like to display formatted java.time.LocalDate in my JSP. Do you know any taglib to use for this?

For java.util.Date we were using <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>. Does something similar for java.time.LocalDate exist?

Answer

Piotr Pradzynski picture Piotr Pradzynski · May 14, 2015

Afsun's hints inspired me to create a quick solution.

  1. Under /WEB-INF create directory tags.
  2. Create tag file localDate.tag inside the tags directory.
  3. Put bellow code into this tag file:

    <%@ tag body-content="empty" pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
    
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <%@ attribute name="date" required="true" type="java.time.LocalDate" %>
    <%@ attribute name="pattern" required="false" type="java.lang.String" %>
    
    <c:if test="${empty pattern}">
        <c:set var="pattern" value="MM/dd/yyyy"/>
    </c:if>
    
    <fmt:parseDate value="${date}" pattern="yyyy-MM-dd" var="parsedDate" type="date"/>
    <fmt:formatDate value="${parsedDate}" type="date" pattern="${pattern}"/>
    
  4. Go to the JSP file in which you want display the java.time.LocalDate.

    4.1. Add taglib directive <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> at the top of the file.

    4.2. Use the localDate tag as follows:

    • <tags:localDate date="${yourDateToPrint}"/>
    • <tags:localDate date="${yourDateToPrint}" pattern="${yourPatternFormat}"/>