Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to show a date as label on a JSF button in customized format?

Tags:

java

jsf

how to show Date(or Timestamp) in customized format on JSF <h:commandButton> ?

I'm using JSF 1.1

like image 666
Chaitanya Gudala Avatar asked Nov 23 '25 03:11

Chaitanya Gudala


1 Answers

The JSF <h:commandButton> doesn't support a converter, neither does it support any text children. You'd either need to perform the job in some helper backing bean method,

<h:commandButton ... value="#{bean.dateInCustomizedFormat}" />

with

public String getDateInCustomizedFormat() {
    return new SimpleDateFormat("yyyy-MM-dd").format(date);
}

or create a reuseable custom EL function for this:

<%@taglib prefix="my" uri="http://example.com/el/functions" %>
...
<h:commandButton ... value="#{my:formatDate(bean.date, 'yyyy-MM-dd')}" />

with

package com.example.el;

import java.text.SimpleDateFormat;
import java.util.Date;

public final class Functions{

    private Functions() {
        // Hide constructor.
    }

    public static String formatDate(Date date, String pattern) {
        Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
        return new SimpleDateFormat(pattern, locale).format(date);
    }

}

and a /WEB-INF/functions.tld (given JSF 1.1, I'll assume that you're still on JSP, not Facelets):

<?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/el/functions</uri>

    <function>
        <name>formatDate</name>
        <function-class>com.example.el.Functions</function-class>
        <function-signature>java.lang.String formatDate(java.util.Date, java.lang.String)</function-signature>
    </function>
</taglib>

(note: if you're using Servlet 2.4/JSP 2.0, replace 2_1 and 2.1 by 2_0 and 2.0 respectively)

like image 54
BalusC Avatar answered Nov 24 '25 17:11

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!