Thursday, July 2, 2009

Date showing wrong in JSF outputText or with dataTable

Some times in , h:outputText with dataTable or without , java.util.Date showing wrong, means one date before the actual date is showing.
We can solve this problem using Converter.
One example :

DateConverter.java

package com.converter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
/**
* This class is is used to convert a date to dd-MMM-yyyy format
* @author jijo
*
*/
public class DateConverter implements Converter {
public String getAsString(FacesContext context, UIComponent c, Object object)
throws ConverterException {
if(object!=null && !object.toString().equals("")){
final Date date = (Date) object;
String dt=null;
if(date!=null){
SimpleDateFormat formatter=new SimpleDateFormat("dd-MMM-yyyy");
dt=formatter.format(date);
return dt;
}}
return null;
}
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
throws ConverterException {
return null;
}
}

In
faces-config.xml
<converter>
<converter-id>dateConvert<converter-id>
<converter-class>com.converter.DateConverter</converter-class>
</converter>



In your jsp page

<h:outputText value="#{item.onDate}" converter="dateConvert" />

1 comment:

abhin said...

thanks.
this is very helping