如何在 p:calendar 中使用 java.time.ZonedDateTime / LocalDateTime
How to use java.time.ZonedDateTime / LocalDateTime in p:calendar
我一直在 Java EE 应用程序中使用 Joda Time 进行日期时间操作,其中相关客户端提交的日期时间的字符串表示在提交之前已使用以下转换例程进行了转换到数据库,即在 JSF 转换器的 getAsObject()
方法中。
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss a Z").withZone(DateTimeZone.UTC);
DateTime dateTime = formatter.parseDateTime("05-Jan-2016 03:04:44 PM +0530");
System.out.println(formatter.print(dateTime));
给定的本地时区比 UTC
/ GMT
早 5 小时 30 分钟。因此,转换为 UTC
应该从使用 Joda Time 正确发生的给定日期时间中减去 5 小时 30 分钟。它按预期显示以下输出。
05-Jan-2016 09:34:44 AM +0000
► 时区偏移量 +0530
代替 +05:30
已被采用,因为它依赖于 <p:calendar>
以这种格式提交时区偏移量。似乎不可能改变 <p:calendar>
的这种行为(否则这个问题本身就不需要了)。
但是,如果尝试使用 Java 中的 Java 时间 API 8.
,同样的事情会被破坏
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a Z").withZone(ZoneOffset.UTC);
ZonedDateTime dateTime = ZonedDateTime.parse("05-Jan-2016 03:04:44 PM +0530", formatter);
System.out.println(formatter.format(dateTime));
它意外地显示了以下不正确的输出。
05-Jan-2016 03:04:44 PM +0000
很明显,转换后的日期时间与UTC
不符。
它需要进行以下更改才能正常工作。
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a z").withZone(ZoneOffset.UTC);
ZonedDateTime dateTime = ZonedDateTime.parse("05-Jan-2016 03:04:44 PM +05:30", formatter);
System.out.println(formatter.format(dateTime));
依次显示以下内容。
05-Jan-2016 09:34:44 AM Z
Z
已替换为 z
,+0530
已替换为 +05:30
。
为什么这两个 API 在这方面有不同的行为在这个问题中完全被忽略了。
对于 <p:calendar>
和 Java 时间在 Java 8 中可以考虑什么中间方法来一致和连贯地工作,尽管 <p:calendar>
内部使用 SimpleDateFormat
连同 java.util.Date
?
JSF 中不成功的测试场景。
转换器:
@FacesConverter("dateTimeConverter")
public class DateTimeConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.isEmpty()) {
return null;
}
try {
return ZonedDateTime.parse(value, DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a Z").withZone(ZoneOffset.UTC));
} catch (IllegalArgumentException | DateTimeException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "Message"), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return "";
}
if (!(value instanceof ZonedDateTime)) {
throw new ConverterException("Message");
}
return DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a z").withZone(ZoneId.of("Asia/Kolkata")).format(((ZonedDateTime) value));
// According to a time zone of a specific user.
}
}
XHTML 具有 <p:calendar>
.
<p:calendar id="dateTime"
timeZone="Asia/Kolkata"
pattern="dd-MMM-yyyy hh:mm:ss a Z"
value="#{bean.dateTime}"
showOn="button"
required="true"
showButtonPanel="true"
navigator="true">
<f:converter converterId="dateTimeConverter"/>
</p:calendar>
<p:message for="dateTime"/>
<p:commandButton value="Submit" update="display" actionListener="#{bean.action}"/><br/><br/>
<h:outputText id="display" value="#{bean.dateTime}">
<f:converter converterId="dateTimeConverter"/>
</h:outputText>
时区完全透明地取决于用户的当前时区。
除了一个 属性.
以外什么都没有的 bean
@ManagedBean
@ViewScoped
public class Bean implements Serializable {
private ZonedDateTime dateTime; // Getter and setter.
private static final long serialVersionUID = 1L;
public Bean() {}
public void action() {
// Do something.
}
}
这将以意想不到的方式工作,如前三个代码片段的倒数第二个示例/中间所示。
具体来说,如果你输入05-Jan-2016 12:00:00 AM +0530
,它会重新显示05-Jan-2016 05:30:00 AM IST
,因为原来在转换器中将05-Jan-2016 12:00:00 AM +0530
转换成UTC
是失败的。
从偏移量为 +05:30
的本地时区转换为 UTC
,然后从 UTC
转换回该时区,显然必须重新显示与通过输入相同的日期时间日历组件,它是给定转换器的基本功能。
更新:
在 java.sql.Timestamp
和 java.time.ZonedDateTime
之间相互转换的 JPA 转换器。
import java.sql.Timestamp;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public final class JodaDateTimeConverter implements AttributeConverter<ZonedDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(ZonedDateTime dateTime) {
return dateTime == null ? null : Timestamp.from(dateTime.toInstant());
}
@Override
public ZonedDateTime convertToEntityAttribute(Timestamp timestamp) {
return timestamp == null ? null : ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneOffset.UTC);
}
}
您的具体问题是您从 Joda 的无区日期时间实例迁移而来 DateTime
to Java8's zoned date time instance ZonedDateTime
instead of Java8's zoneless date time instance LocalDateTime
。
使用 ZonedDateTime
(或 OffsetDateTime
)代替 LocalDateTime
需要至少 2 个额外的更改:
在日期时间转换期间不要强制使用时区(偏移量)。相反,输入字符串的时区(如果有)将在解析期间使用,并且存储在 ZonedDateTime
实例中的时区必须在格式化期间使用。
DateTimeFormatter#withZone()
只会给出与 ZonedDateTime
混淆的结果,因为它将在解析过程中充当后备(仅在输入字符串或格式模式中不存在时区时使用),并且它将在格式化期间充当覆盖(存储在 ZonedDateTime
中的时区被完全忽略)。这是您可观察到的问题的根本原因。只需在创建格式化程序时省略 withZone()
即可解决此问题。
请注意,如果您指定了一个转换器,但没有 timeOnly="true"
,那么您不需要指定 <p:calendar timeZone>
。即使你这样做了,你也宁愿使用 TimeZone.getTimeZone(zonedDateTime.getZone())
而不是对其进行硬编码。
您需要在所有层上携带时区(偏移量),包括数据库。但是,如果您的数据库具有“没有时区的日期时间”列类型,则时区信息在持久化期间会丢失,并且您将 运行 在从数据库返回时遇到麻烦。
不清楚您使用的是哪个数据库,但请记住,某些数据库不支持 Oracle and PostgreSQL DBs. For example, MySQL does not support it 中已知的 TIMESTAMP WITH TIME ZONE
列类型。您需要第二列。
如果这些更改不可接受,那么您需要退回到 LocalDateTime
并在所有层(包括数据库)中依赖 fixed/predefined 时区。通常使用 UTC。
在 JSF 和 JPA 中处理 ZonedDateTime
当使用 ZonedDateTime
和适当的 TIMESTAMP WITH TIME ZONE
数据库列类型时,使用下面的 JSF 转换器在 UI 和 ZonedDateTime
中的 String
之间进行转换在模型中。该转换器将从父组件中查找 pattern
和 locale
属性。如果父组件本身不支持 pattern
或 locale
属性,只需将它们添加为 <f:attribute name="..." value="...">
。如果 locale
属性不存在,将使用(默认)<f:view locale>
代替。 没有 timeZone
属性,原因如上文#1 所述。
@FacesConverter(forClass=ZonedDateTime.class)
public class ZonedDateTimeConverter implements Converter {
@Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
if (modelValue instanceof ZonedDateTime) {
return getFormatter(context, component).format((ZonedDateTime) modelValue);
} else {
throw new ConverterException(new FacesMessage(modelValue + " is not a valid ZonedDateTime"));
}
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
return ZonedDateTime.parse(submittedValue, getFormatter(context, component));
} catch (DateTimeParseException e) {
throw new ConverterException(new FacesMessage(submittedValue + " is not a valid zoned date time"), e);
}
}
private DateTimeFormatter getFormatter(FacesContext context, UIComponent component) {
return DateTimeFormatter.ofPattern(getPattern(component), getLocale(context, component));
}
private String getPattern(UIComponent component) {
String pattern = (String) component.getAttributes().get("pattern");
if (pattern == null) {
throw new IllegalArgumentException("pattern attribute is required");
}
return pattern;
}
private Locale getLocale(FacesContext context, UIComponent component) {
Object locale = component.getAttributes().get("locale");
return (locale instanceof Locale) ? (Locale) locale
: (locale instanceof String) ? new Locale((String) locale)
: context.getViewRoot().getLocale();
}
}
并使用下面的 JPA 转换器在模型中的 ZonedDateTime
和 JDBC 中的 java.util.Calendar
之间进行转换(体面的 JDBC 驱动程序将 require/use 它对于 TIMESTAMP WITH TIME ZONE
类型的列):
@Converter(autoApply=true)
public class ZonedDateTimeAttributeConverter implements AttributeConverter<ZonedDateTime, Calendar> {
@Override
public Calendar convertToDatabaseColumn(ZonedDateTime entityAttribute) {
if (entityAttribute == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(entityAttribute.toInstant().toEpochMilli());
calendar.setTimeZone(TimeZone.getTimeZone(entityAttribute.getZone()));
return calendar;
}
@Override
public ZonedDateTime convertToEntityAttribute(Calendar databaseColumn) {
if (databaseColumn == null) {
return null;
}
return ZonedDateTime.ofInstant(databaseColumn.toInstant(), databaseColumn.getTimeZone().toZoneId());
}
}
在 JSF 和 JPA 中处理 LocalDateTime
当使用基于 UTC 的 LocalDateTime
和适当的基于 UTC 的 TIMESTAMP
(没有时区!)数据库列类型时,使用下面的 JSF 转换器在 String
之间进行转换 UI 和 LocalDateTime
在模型中。该转换器将从父组件中查找 pattern
、timeZone
和 locale
属性。如果父组件本身不支持 pattern
、timeZone
and/or locale
属性,只需将它们添加为 <f:attribute name="..." value="...">
。 timeZone
属性必须表示输入字符串的回退时区(当 pattern
不包含时区时)和输出字符串的时区。
@FacesConverter(forClass=LocalDateTime.class)
public class LocalDateTimeConverter implements Converter {
@Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
if (modelValue instanceof LocalDateTime) {
return getFormatter(context, component).format(ZonedDateTime.of((LocalDateTime) modelValue, ZoneOffset.UTC));
} else {
throw new ConverterException(new FacesMessage(modelValue + " is not a valid LocalDateTime"));
}
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
return ZonedDateTime.parse(submittedValue, getFormatter(context, component)).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
} catch (DateTimeParseException e) {
throw new ConverterException(new FacesMessage(submittedValue + " is not a valid local date time"), e);
}
}
private DateTimeFormatter getFormatter(FacesContext context, UIComponent component) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(getPattern(component), getLocale(context, component));
ZoneId zone = getZoneId(component);
return (zone != null) ? formatter.withZone(zone) : formatter;
}
private String getPattern(UIComponent component) {
String pattern = (String) component.getAttributes().get("pattern");
if (pattern == null) {
throw new IllegalArgumentException("pattern attribute is required");
}
return pattern;
}
private Locale getLocale(FacesContext context, UIComponent component) {
Object locale = component.getAttributes().get("locale");
return (locale instanceof Locale) ? (Locale) locale
: (locale instanceof String) ? new Locale((String) locale)
: context.getViewRoot().getLocale();
}
private ZoneId getZoneId(UIComponent component) {
Object timeZone = component.getAttributes().get("timeZone");
return (timeZone instanceof TimeZone) ? ((TimeZone) timeZone).toZoneId()
: (timeZone instanceof String) ? ZoneId.of((String) timeZone)
: null;
}
}
并使用下面的 JPA 转换器在模型中的 LocalDateTime
和 JDBC 中的 java.sql.Timestamp
之间进行转换(体面的 JDBC 驱动程序将 require/use 它对于 TIMESTAMP
类型的列):
@Converter(autoApply=true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime entityAttribute) {
if (entityAttribute == null) {
return null;
}
return Timestamp.valueOf(entityAttribute);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp databaseColumn) {
if (databaseColumn == null) {
return null;
}
return databaseColumn.toLocalDateTime();
}
}
将 LocalDateTimeConverter
应用到您的特定案例 <p:calendar>
您需要更改以下内容:
由于 <p:calendar>
不通过 forClass
查找转换器,您需要 re-register 它与 <converter><converter-id>localDateTimeConverter
在 faces-config.xml
, 或改变注解如下
@FacesConverter("localDateTimeConverter")
由于没有 timeOnly="true"
的 <p:calendar>
会忽略 timeZone
,并在弹出窗口中提供编辑它的选项,因此您需要删除 timeZone
属性以避免转换器混淆(仅当 pattern
中不存在时区时才需要此属性)。
您需要在输出时指定想要显示的timeZone
属性(使用ZonedDateTimeConverter
时不需要此属性,因为它已经存储在ZonedDateTime
中)。
这是完整的工作片段:
<p:calendar id="dateTime"
pattern="dd-MMM-yyyy hh:mm:ss a Z"
value="#{bean.dateTime}"
showOn="button"
required="true"
showButtonPanel="true"
navigator="true">
<f:converter converterId="localDateTimeConverter" />
</p:calendar>
<p:message for="dateTime" autoUpdate="true" />
<p:commandButton value="Submit" update="display" action="#{bean.action}" /><br/><br/>
<h:outputText id="display" value="#{bean.dateTime}">
<f:converter converterId="localDateTimeConverter" />
<f:attribute name="pattern" value="dd-MMM-yyyy hh:mm:ss a Z" />
<f:attribute name="timeZone" value="Asia/Kolkata" />
</h:outputText>
如果您打算创建自己的带有属性的 <my:convertLocalDateTime>
,您需要将它们作为带有 getters/setters 的 bean-like 属性添加到转换器 class 并且如本答案所示,在 *.taglib.xml
中注册它:Creating custom tag for Converter with attributes
<h:outputText id="display" value="#{bean.dateTime}">
<my:convertLocalDateTime pattern="dd-MMM-yyyy hh:mm:ss a Z"
timeZone="Asia/Kolkata" />
</h:outputText>
我一直在 Java EE 应用程序中使用 Joda Time 进行日期时间操作,其中相关客户端提交的日期时间的字符串表示在提交之前已使用以下转换例程进行了转换到数据库,即在 JSF 转换器的 getAsObject()
方法中。
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss a Z").withZone(DateTimeZone.UTC);
DateTime dateTime = formatter.parseDateTime("05-Jan-2016 03:04:44 PM +0530");
System.out.println(formatter.print(dateTime));
给定的本地时区比 UTC
/ GMT
早 5 小时 30 分钟。因此,转换为 UTC
应该从使用 Joda Time 正确发生的给定日期时间中减去 5 小时 30 分钟。它按预期显示以下输出。
05-Jan-2016 09:34:44 AM +0000
► 时区偏移量 +0530
代替 +05:30
已被采用,因为它依赖于 <p:calendar>
以这种格式提交时区偏移量。似乎不可能改变 <p:calendar>
的这种行为(否则这个问题本身就不需要了)。
但是,如果尝试使用 Java 中的 Java 时间 API 8.
,同样的事情会被破坏java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a Z").withZone(ZoneOffset.UTC);
ZonedDateTime dateTime = ZonedDateTime.parse("05-Jan-2016 03:04:44 PM +0530", formatter);
System.out.println(formatter.format(dateTime));
它意外地显示了以下不正确的输出。
05-Jan-2016 03:04:44 PM +0000
很明显,转换后的日期时间与UTC
不符。
它需要进行以下更改才能正常工作。
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a z").withZone(ZoneOffset.UTC);
ZonedDateTime dateTime = ZonedDateTime.parse("05-Jan-2016 03:04:44 PM +05:30", formatter);
System.out.println(formatter.format(dateTime));
依次显示以下内容。
05-Jan-2016 09:34:44 AM Z
Z
已替换为 z
,+0530
已替换为 +05:30
。
为什么这两个 API 在这方面有不同的行为在这个问题中完全被忽略了。
对于 <p:calendar>
和 Java 时间在 Java 8 中可以考虑什么中间方法来一致和连贯地工作,尽管 <p:calendar>
内部使用 SimpleDateFormat
连同 java.util.Date
?
JSF 中不成功的测试场景。
转换器:
@FacesConverter("dateTimeConverter")
public class DateTimeConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.isEmpty()) {
return null;
}
try {
return ZonedDateTime.parse(value, DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a Z").withZone(ZoneOffset.UTC));
} catch (IllegalArgumentException | DateTimeException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "Message"), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return "";
}
if (!(value instanceof ZonedDateTime)) {
throw new ConverterException("Message");
}
return DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss a z").withZone(ZoneId.of("Asia/Kolkata")).format(((ZonedDateTime) value));
// According to a time zone of a specific user.
}
}
XHTML 具有 <p:calendar>
.
<p:calendar id="dateTime"
timeZone="Asia/Kolkata"
pattern="dd-MMM-yyyy hh:mm:ss a Z"
value="#{bean.dateTime}"
showOn="button"
required="true"
showButtonPanel="true"
navigator="true">
<f:converter converterId="dateTimeConverter"/>
</p:calendar>
<p:message for="dateTime"/>
<p:commandButton value="Submit" update="display" actionListener="#{bean.action}"/><br/><br/>
<h:outputText id="display" value="#{bean.dateTime}">
<f:converter converterId="dateTimeConverter"/>
</h:outputText>
时区完全透明地取决于用户的当前时区。
除了一个 属性.
以外什么都没有的 bean@ManagedBean
@ViewScoped
public class Bean implements Serializable {
private ZonedDateTime dateTime; // Getter and setter.
private static final long serialVersionUID = 1L;
public Bean() {}
public void action() {
// Do something.
}
}
这将以意想不到的方式工作,如前三个代码片段的倒数第二个示例/中间所示。
具体来说,如果你输入05-Jan-2016 12:00:00 AM +0530
,它会重新显示05-Jan-2016 05:30:00 AM IST
,因为原来在转换器中将05-Jan-2016 12:00:00 AM +0530
转换成UTC
是失败的。
从偏移量为 +05:30
的本地时区转换为 UTC
,然后从 UTC
转换回该时区,显然必须重新显示与通过输入相同的日期时间日历组件,它是给定转换器的基本功能。
更新:
在 java.sql.Timestamp
和 java.time.ZonedDateTime
之间相互转换的 JPA 转换器。
import java.sql.Timestamp;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public final class JodaDateTimeConverter implements AttributeConverter<ZonedDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(ZonedDateTime dateTime) {
return dateTime == null ? null : Timestamp.from(dateTime.toInstant());
}
@Override
public ZonedDateTime convertToEntityAttribute(Timestamp timestamp) {
return timestamp == null ? null : ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneOffset.UTC);
}
}
您的具体问题是您从 Joda 的无区日期时间实例迁移而来 DateTime
to Java8's zoned date time instance ZonedDateTime
instead of Java8's zoneless date time instance LocalDateTime
。
使用 ZonedDateTime
(或 OffsetDateTime
)代替 LocalDateTime
需要至少 2 个额外的更改:
在日期时间转换期间不要强制使用时区(偏移量)。相反,输入字符串的时区(如果有)将在解析期间使用,并且存储在
ZonedDateTime
实例中的时区必须在格式化期间使用。DateTimeFormatter#withZone()
只会给出与ZonedDateTime
混淆的结果,因为它将在解析过程中充当后备(仅在输入字符串或格式模式中不存在时区时使用),并且它将在格式化期间充当覆盖(存储在ZonedDateTime
中的时区被完全忽略)。这是您可观察到的问题的根本原因。只需在创建格式化程序时省略withZone()
即可解决此问题。请注意,如果您指定了一个转换器,但没有
timeOnly="true"
,那么您不需要指定<p:calendar timeZone>
。即使你这样做了,你也宁愿使用TimeZone.getTimeZone(zonedDateTime.getZone())
而不是对其进行硬编码。您需要在所有层上携带时区(偏移量),包括数据库。但是,如果您的数据库具有“没有时区的日期时间”列类型,则时区信息在持久化期间会丢失,并且您将 运行 在从数据库返回时遇到麻烦。
不清楚您使用的是哪个数据库,但请记住,某些数据库不支持 Oracle and PostgreSQL DBs. For example, MySQL does not support it 中已知的
TIMESTAMP WITH TIME ZONE
列类型。您需要第二列。
如果这些更改不可接受,那么您需要退回到 LocalDateTime
并在所有层(包括数据库)中依赖 fixed/predefined 时区。通常使用 UTC。
在 JSF 和 JPA 中处理 ZonedDateTime
当使用 ZonedDateTime
和适当的 TIMESTAMP WITH TIME ZONE
数据库列类型时,使用下面的 JSF 转换器在 UI 和 ZonedDateTime
中的 String
之间进行转换在模型中。该转换器将从父组件中查找 pattern
和 locale
属性。如果父组件本身不支持 pattern
或 locale
属性,只需将它们添加为 <f:attribute name="..." value="...">
。如果 locale
属性不存在,将使用(默认)<f:view locale>
代替。 没有 timeZone
属性,原因如上文#1 所述。
@FacesConverter(forClass=ZonedDateTime.class)
public class ZonedDateTimeConverter implements Converter {
@Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
if (modelValue instanceof ZonedDateTime) {
return getFormatter(context, component).format((ZonedDateTime) modelValue);
} else {
throw new ConverterException(new FacesMessage(modelValue + " is not a valid ZonedDateTime"));
}
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
return ZonedDateTime.parse(submittedValue, getFormatter(context, component));
} catch (DateTimeParseException e) {
throw new ConverterException(new FacesMessage(submittedValue + " is not a valid zoned date time"), e);
}
}
private DateTimeFormatter getFormatter(FacesContext context, UIComponent component) {
return DateTimeFormatter.ofPattern(getPattern(component), getLocale(context, component));
}
private String getPattern(UIComponent component) {
String pattern = (String) component.getAttributes().get("pattern");
if (pattern == null) {
throw new IllegalArgumentException("pattern attribute is required");
}
return pattern;
}
private Locale getLocale(FacesContext context, UIComponent component) {
Object locale = component.getAttributes().get("locale");
return (locale instanceof Locale) ? (Locale) locale
: (locale instanceof String) ? new Locale((String) locale)
: context.getViewRoot().getLocale();
}
}
并使用下面的 JPA 转换器在模型中的 ZonedDateTime
和 JDBC 中的 java.util.Calendar
之间进行转换(体面的 JDBC 驱动程序将 require/use 它对于 TIMESTAMP WITH TIME ZONE
类型的列):
@Converter(autoApply=true)
public class ZonedDateTimeAttributeConverter implements AttributeConverter<ZonedDateTime, Calendar> {
@Override
public Calendar convertToDatabaseColumn(ZonedDateTime entityAttribute) {
if (entityAttribute == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(entityAttribute.toInstant().toEpochMilli());
calendar.setTimeZone(TimeZone.getTimeZone(entityAttribute.getZone()));
return calendar;
}
@Override
public ZonedDateTime convertToEntityAttribute(Calendar databaseColumn) {
if (databaseColumn == null) {
return null;
}
return ZonedDateTime.ofInstant(databaseColumn.toInstant(), databaseColumn.getTimeZone().toZoneId());
}
}
在 JSF 和 JPA 中处理 LocalDateTime
当使用基于 UTC 的 LocalDateTime
和适当的基于 UTC 的 TIMESTAMP
(没有时区!)数据库列类型时,使用下面的 JSF 转换器在 String
之间进行转换 UI 和 LocalDateTime
在模型中。该转换器将从父组件中查找 pattern
、timeZone
和 locale
属性。如果父组件本身不支持 pattern
、timeZone
and/or locale
属性,只需将它们添加为 <f:attribute name="..." value="...">
。 timeZone
属性必须表示输入字符串的回退时区(当 pattern
不包含时区时)和输出字符串的时区。
@FacesConverter(forClass=LocalDateTime.class)
public class LocalDateTimeConverter implements Converter {
@Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
if (modelValue instanceof LocalDateTime) {
return getFormatter(context, component).format(ZonedDateTime.of((LocalDateTime) modelValue, ZoneOffset.UTC));
} else {
throw new ConverterException(new FacesMessage(modelValue + " is not a valid LocalDateTime"));
}
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
return ZonedDateTime.parse(submittedValue, getFormatter(context, component)).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
} catch (DateTimeParseException e) {
throw new ConverterException(new FacesMessage(submittedValue + " is not a valid local date time"), e);
}
}
private DateTimeFormatter getFormatter(FacesContext context, UIComponent component) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(getPattern(component), getLocale(context, component));
ZoneId zone = getZoneId(component);
return (zone != null) ? formatter.withZone(zone) : formatter;
}
private String getPattern(UIComponent component) {
String pattern = (String) component.getAttributes().get("pattern");
if (pattern == null) {
throw new IllegalArgumentException("pattern attribute is required");
}
return pattern;
}
private Locale getLocale(FacesContext context, UIComponent component) {
Object locale = component.getAttributes().get("locale");
return (locale instanceof Locale) ? (Locale) locale
: (locale instanceof String) ? new Locale((String) locale)
: context.getViewRoot().getLocale();
}
private ZoneId getZoneId(UIComponent component) {
Object timeZone = component.getAttributes().get("timeZone");
return (timeZone instanceof TimeZone) ? ((TimeZone) timeZone).toZoneId()
: (timeZone instanceof String) ? ZoneId.of((String) timeZone)
: null;
}
}
并使用下面的 JPA 转换器在模型中的 LocalDateTime
和 JDBC 中的 java.sql.Timestamp
之间进行转换(体面的 JDBC 驱动程序将 require/use 它对于 TIMESTAMP
类型的列):
@Converter(autoApply=true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime entityAttribute) {
if (entityAttribute == null) {
return null;
}
return Timestamp.valueOf(entityAttribute);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp databaseColumn) {
if (databaseColumn == null) {
return null;
}
return databaseColumn.toLocalDateTime();
}
}
将 LocalDateTimeConverter
应用到您的特定案例 <p:calendar>
您需要更改以下内容:
由于
<p:calendar>
不通过forClass
查找转换器,您需要 re-register 它与<converter><converter-id>localDateTimeConverter
在faces-config.xml
, 或改变注解如下@FacesConverter("localDateTimeConverter")
由于没有
timeOnly="true"
的<p:calendar>
会忽略timeZone
,并在弹出窗口中提供编辑它的选项,因此您需要删除timeZone
属性以避免转换器混淆(仅当pattern
中不存在时区时才需要此属性)。您需要在输出时指定想要显示的
timeZone
属性(使用ZonedDateTimeConverter
时不需要此属性,因为它已经存储在ZonedDateTime
中)。
这是完整的工作片段:
<p:calendar id="dateTime"
pattern="dd-MMM-yyyy hh:mm:ss a Z"
value="#{bean.dateTime}"
showOn="button"
required="true"
showButtonPanel="true"
navigator="true">
<f:converter converterId="localDateTimeConverter" />
</p:calendar>
<p:message for="dateTime" autoUpdate="true" />
<p:commandButton value="Submit" update="display" action="#{bean.action}" /><br/><br/>
<h:outputText id="display" value="#{bean.dateTime}">
<f:converter converterId="localDateTimeConverter" />
<f:attribute name="pattern" value="dd-MMM-yyyy hh:mm:ss a Z" />
<f:attribute name="timeZone" value="Asia/Kolkata" />
</h:outputText>
如果您打算创建自己的带有属性的 <my:convertLocalDateTime>
,您需要将它们作为带有 getters/setters 的 bean-like 属性添加到转换器 class 并且如本答案所示,在 *.taglib.xml
中注册它:Creating custom tag for Converter with attributes
<h:outputText id="display" value="#{bean.dateTime}">
<my:convertLocalDateTime pattern="dd-MMM-yyyy hh:mm:ss a Z"
timeZone="Asia/Kolkata" />
</h:outputText>