JSF Tutorial - JSF Convert Date Time Example








f:convertDateTime tag is used to convert a string value to a date of required format. It also acts as a validator a required date format.

The following code shows how to use use the f:convertDateTime tag.

<f:convertDateTime pattern="dd-mm-yyyy" />

Tag Attributes

AttributeDescription
typedate (default), time, or both
dateStyledefault, short, medium, long, or full
timeStyledefault, short, medium, long, or full
patternFormatting pattern, as defined in java.text.SimpleDateFormat
localeLocale whose preferences are to be used for parsing and formatting
timeZoneTime zone to use for parsing and formatting




Example

The following code is from result.xhtml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:c="http://java.sun.com/jsp/jstl/core">
    <h:body>
      Receipt Date :  
      <h:outputText value="#{receipt.date}" >
        <f:convertDateTime pattern="d-M-yyyy" />
      </h:outputText>
      
    </h:body>
</html>

The following code is from demo.xhtml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      >
    <h:body>
    <h:form>
      <h:panelGrid columns="3">
        Receipt Date : 
        <h:inputText id="date" value="#{receipt.date}" 
          size="20" required="true"
          label="Receipt Date" >
          <f:convertDateTime pattern="d-M-yyyy" />
        </h:inputText>
        <h:message for="date" style="color:red" />
      </h:panelGrid>
      <h:commandButton value="Submit" action="result" />
    </h:form>
    </h:body>
</html>

The following code is from UserBean.java.

package com.java2s.common;

import java.io.Serializable;
import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="receipt")
@SessionScoped
public class UserBean implements Serializable{
  
  private static final long serialVersionUID = 1L;
  
  Date date;

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }

}


Download Convert_Date_Time.zip





To RUN

Copy the generated WAR file from the target folder to Tomcat deployment folder and run Tomcat-Install-folder/bin/startup.bat.

After Tomcat finish starting, type the following URL in the browser address bar.

http://localhost:8080/simple-webapp/demo.xhtml