基本转换器(仅为原型)在
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: 日历>
正在提交的组件本身或正在提交的同一表单上的某些其他组件在转换/验证过程中失败,在这种情况下,日历组件将预先填充本地化的日期时间,该日期时间将无法转换为
获取AsObject()
除非给定的本地化日期时间
<p: 日历>
手动重置为默认区域设置。
由于没有转换/验证违规,下面将传递第一次提交表单的尝试。
然而,如果在如下字段之一中存在转换错误,
然后,日历组件中的两个日期都将根据所选区域设置进行更改(
hi_IN
),因为其中一个字段存在转换错误,显然无法在
获取AsObject()
在随后的尝试中,如果在通过为字段提供正确的值来修复转换错误之后试图提交包含组件的表单。
有什么建议吗?