JSTL LocalDateTime format

Ugur Artun picture Ugur Artun · Feb 24, 2016 · Viewed 17.5k times · Source

I want to format my Java 8 LocalDateTime object in "dd.MM.yyyy" pattern. Is there any library to format? I tried code below but got conversion exception.

<fmt:parseDate value="${date}" pattern="yyyy-MM-dd" var="parsedDate" type="date" />

Is there any tag or converter for LocalDateTime class in JSTL?

Answer

BalusC picture BalusC · Feb 24, 2016

It doesn't exist in the 14-year old JSTL.

Your best bet is creating a custom EL function. First create an utility method.

package com.example;

public final class Dates {
     private Dates() {}

     public static String formatLocalDateTime(LocalDateTime localDateTime, String pattern) {
         return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
     }
}

Then create a /WEB-INF/functions.tld wherein you register the utility method as an EL function:

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">

    <tlib-version>1.0</tlib-version>
    <short-name>Custom_Functions</short-name>
    <uri>http://example.com/functions</uri>

    <function>
        <name>formatLocalDateTime</name>
        <function-class>com.example.Dates</function-class>
        <function-signature>java.lang.String formatLocalDateTime(java.time.LocalDateTime, java.lang.String)</function-signature>
    </function>
</taglib>

Finally use it as below:

<%@taglib uri="http://example.com/functions" prefix="f" %>

<p>Date is: ${f:formatLocalDateTime(date, 'dd.MM.yyyy')}</p>

Extend if necessary the method to take a Locale argument.