JSP tutorial : custom format

By , last updated November 14, 2019

I’ve come around a problem when I needed to format DateMidnight date in JSP. Here I’ll explain 2 ways of doing this, where the other one applies only to joda.

A. Make a custom tag

1) Make a “WEB-INF/tags/formatDateMidnight.tag”, with the following code:

<%@ tag isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ attribute name="date" type="org.joda.time.DateMidnight" required="true" %>

<fmt:parseDate value="${date.dayOfMonth}/${date.monthOfYear}/${date.year}" pattern="dd/MM/yyyy" var="homersBirthday"/>  
<fmt:formatDate value="${homersBirthday}" pattern="dd.MM.yyyy"/>

2) Add the tag to your page:

<%@ taglib tagdir="/WEB-INF/tags" prefix="s" %>

3) Use it:

<s:formatDateMidnight date="${attribute.date}"/>

B. Use Joda time JSP tags support

1) Import Joda tags support:

<dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time-jsptags</artifactId>
            <version>1.0</version>
</dependency>

2) Add the tag to your page:

<%@taglib prefix="joda" uri="http://www.joda.org/joda/time/tags" %>

3) Use it:

<joda:format pattern="dd.MM.yyyy" value="${attribute.date}"/>