【发布时间】:2016-04-29 14:00:37
【问题描述】:
在String 和java.time.LocalDateTime 之间来回转换的基本转换器(只是一个原型)。
@FacesConverter("localDateTimeConverter")
public class LocalDateTimeConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
return ZonedDateTime.parse(submittedValue, DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime());
} catch (IllegalArgumentException | DateTimeException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "Message"), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
if (!(modelValue instanceof LocalDateTime)) {
throw new ConverterException("Message");
}
Locale locale = context.getViewRoot().getLocale();
return DateTimeFormatter.ofPattern(pattern, locale).withZone(ZoneId).format(ZonedDateTime.of((LocalDateTime) modelValue, ZoneOffset.UTC));
}
}
要提交到数据库的日期时间应基于Locale.ENGLISH。因此,它在getAsObject() 中是常量/静态的。
从数据库中检索的日期时间,即呈现给最终用户的日期时间基于用户选择的选定区域设置。因此,Locale 在getAsString() 中是动态的。
日期时间使用<p:calendar>提交,未本地化以避免麻烦。
这将按预期工作,除非<p:calendar> 组件本身提交或同一表单上的某些其他组件在转换/验证期间失败,在这种情况下,日历组件将预先填充本地化的日期时间除非手动将给定 <p:calendar> 中的本地化日期时间重置为默认语言环境,否则在所有后续尝试提交表单时将无法在 getAsObject() 中转换。
以下将通过第一次尝试提交表单,因为没有转换/验证违规。
但是,如果以下字段之一出现转换错误,
那么日历组件中的两个日期都将根据所选的语言环境 (hi_IN) 进行更改,因为其中一个字段存在转换错误,在随后的尝试中显然无法在 getAsObject() 中转换, 如果在通过为字段提供正确值来修复转换错误后尝试提交包含组件的表单。
有什么建议吗?
【问题讨论】: