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?
To format the localdate in any other custom pattern, we must use LocalDate. format(DateTimeFormatter) method. LocalDate today = LocalDate. now(); String formattedDate = today.
now() now() method of a LocalDate class used to obtain the current date from the system clock in the default time-zone. This method will return LocalDate based on system clock with default time-zone to obtain the current date. Syntax: public static LocalDate now()
LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date.
A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03 . LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day.
Afsun's hints inspired me to create a quick solution.
/WEB-INF
create directory tags
.localDate.tag
inside the tags
directory.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}"/>
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}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With