f:convertDateTime支持Java8 LocalDate / LocalDateTime?
JSF核心标记f:convertDateTime可以格式化java.util.Date对象。 Date类有许多不推荐使用的方法,Java 8提供了新类来显示本地日期和时间: LocalDateTime和LocalDate 。
f:convertDateTime无法格式化LocalDateTime或LocalDate 。
有没有人知道,如果有一个等价的JSF核心标记convertDateTime可以处理LocalDateTime对象? 计划是为将来的版本提供支持,还是提供替代标签?
编写自己的Converter并扩展javax.faces.convert.DateTimeConverter
– 这样就可以重用
支持的所有属性。 它也会照顾本地化。 不幸的是,编写带属性的转换器有点复杂。
- 编写自己的扩展
javax.faces.convert.DateTimeConverter
的Converter – 让超级调用完成所有工作(包括locale-stuff)并将结果从/转换为LocalDate。
@FacesConverter(value = LocalDateConverter.ID) public class LocalDateConverter extends DateTimeConverter { public static final String ID =“com.example.LocalDateConverter”; @覆盖 public Object getAsObject(FacesContext facesContext, UIComponent uiComponent,String value){ LocalDate ldate = null; 日期日期= null; Object o = super.getAsObject(facesContext,uiComponent,value); if(o == null){ return null; } if(o instanceof Date){ date =(Date)o; 即时瞬间= Instant.ofEpochMilli(date.getTime()); ldate = LocalDateTime.ofInstant(instant,ZoneId.systemDefault())。toLocalDate(); 返回ldate; } 其他{ 抛出新的IllegalArgumentException(String.format(“value =%s无法转换为LocalDate,结果super.getAsObject =%s”,value,o)); } } @覆盖 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)值; Instant instant = lDate.atStartOfDay()。atZone(ZoneId.systemDefault())。toInstant(); 日期日期= Date.from(即时); return super.getAsString(facesContext,uiComponent,date); } 其他{ 抛出新的IllegalArgumentException(String.format(“value =%s不是localof的实例”,值)); } } }
- 在
META-INF
创建一个文件LocalDateConverter-taglib.xml
:
<命名空间> http://example.com/LocalDateConverter 命名空间> <标签> <标签名称> convertLocalDate 标签名称> <变换器> <变换器-ID> com.example.LocalDateConverter 转换器-ID> 转换器> 标签> 的facelet-标签库>
- 在
web.xml
注册taglib:
<的context-param> facelets.LIBRARIES PARAM名称> /META-INF/LocalDateConverter-taglib.xml PARAM值> 的context-param>
- 要在JSF页面中使用新标记,请添加新的Taglib
xmlns:ldc="http://example.com/LocalDateConverter"
然后你可以使用Tag
。