date convert to calendar converter using p:calendar

Posted: August 27, 2012 in web

xhtml

<p:calendar pattern=”MM/dd/yyyy” value=”#{bean.startDate}” showOn=”button” mode=”popup” converter=”#{calendarConverter}” />

CalendarConverter

@Named
@FacesConverter(forClass = Date.class)
public class CalendarConverter implements Converter {

@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
SimpleDateFormat formatter = new SimpleDateFormat(“MM/dd/yyyy”);
try {
Date date = (Date) formatter.parse(value);
Calendar cDate = Calendar.getInstance();
cDate.setTime(date);
return cDate;
} catch (Exception e) {
return null;
}
}

@Override
public String getAsString(FacesContext context, UIComponent component, Object object) {
SimpleDateFormat formatter = new SimpleDateFormat(“MM/dd/yyyy”);
StringBuilder date = new StringBuilder(formatter.format(((Calendar) object).getTime()));
return date.toString();
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s