Just write your own Converter and extend the javax.faces.convert.DateTimeConverter
- that way you can Reuse all the attributes that
supports. Also it will take care of Localization too. Unfortunately it's a bit more complicated to write a Converter with Attributes.
Create component
First write your own Converter that extends javax.faces.convert.DateTimeConverter
- just let the super-calls do all the work (including locale-stuff) and convert the result from/to LocalDate.
@FacesConverter(value = LocalDateConverter.ID)
public class LocalDateConverter extends DateTimeConverter {
public static final String ID = "com.example.LocalDateConverter";
@Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
Object o = super.getAsObject(facesContext, uiComponent, value);
if (o == null) {
return null;
}
if (o instanceof Date) {
Instant instant = Instant.ofEpochMilli(((Date) o).getTime());
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();
} else {
throw new IllegalArgumentException(String.format("value=%s could not be converted to a LocalDate, result super.getAsObject=%s", value, o));
}
}
@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
if (value == null) {
return super.getAsString(facesContext, uiComponent,value);
}
if (value instanceof LocalDate) {
LocalDate lDate = (LocalDate) value;
Instant instant = lDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
return super.getAsString(facesContext, uiComponent, date);
} else {
throw new IllegalArgumentException(String.format("value=%s is not a instanceof LocalDate", value));
}
}
}
Then create a file LocalDateConverter-taglib.xml
in META-INF
:
http://example.com/LocalDateConverter
convertLocalDate
com.example.LocalDateConverter
And lastly, register the taglib in web.xml
:
javax.faces.FACELETS_LIBRARIES
/META-INF/LocalDateConverter-taglib.xml
Usage
To use the new Tag in your JSF-Page add the new Taglib xmlns:ldc="http://example.com/LocalDateConverter"
and use the tag: