gpt4 book ai didi

jsf - 如何在 p :calendar 中使用 java.time.ZonedDateTime/LocalDateTime

转载 作者:行者123 更新时间:2023-12-03 11:36:51 28 4
gpt4 key购买 nike

我一直在 Java EE 应用程序中使用 Joda Time 进行日期时间操作,其中关联客户端提交的日期时间字符串表示已使用以下转换例程进行转换,然后再将其提交到数据库,即在 getAsObject() 中。 JSF 转换器中的方法。

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 提前 5 小时 30 分钟/ GMT .因此,转换为 UTC应该从使用 Joda 时间正确发生的给定日期时间中减去 5 小时 30 分钟。它按预期显示以下输出。
05-Jan-2016 09:34:44 AM +0000

► 时区偏移 +0530代替 +05:30已被采用,因为它依赖于 <p:calendar>以这种格式提交区域偏移量。似乎不可能改变 <p:calendar> 的这种行为。 (否则就不需要这个问题本身)。

然而,如果尝试在 Java 8 中使用 Java Time API,同样的事情就会被破坏。
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 8 中的 Java Time 可以一致且连贯地工作 <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 相互转换的 JPA 转换器和 java.time.ZonedDateTime .
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 到 Java8 的分区日期时间实例 ZonedDateTime 而不是 Java8 的无区域日期时间实例 LocalDateTime .
使用 ZonedDateTime (或 OffsetDateTime )而不是 LocalDateTime需要至少 2 个额外的更改:

  • 在日期时间转换期间不要强制使用时区(偏移量) .相反,输入字符串的时区(如果有)将在解析过程中使用,时区存储在 ZonedDateTime 中。在格式化期间必须使用实例。
    DateTimeFormatter#withZone() 只会用 ZonedDateTime 给出令人困惑的结果因为它将在解析过程中充当回退(它仅在输入字符串或格式模式中不存在时区时使用),并且在格式化过程中将充当覆盖(存储在 ZonedDateTime 中的时区被完全忽略)。这是您的可观察问题的根本原因。只是省略withZone()在创建格式化程序时应该修复它。
    请注意,当您指定了转换器时,并且没有 timeOnly="true" ,那么您不需要指定 <p:calendar timeZone> .即使您这样做,您也更愿意使用 TimeZone.getTimeZone(zonedDateTime.getZone())而不是对其进行硬编码。
  • 您需要在所有层中携带时区(偏移量),包括数据库 .但是,如果您的数据库具有“没有时区的日期时间”列类型,则时区信息在持久化期间会丢失,并且在从数据库返回服务时会遇到麻烦。
    不清楚您使用的是哪个数据库,但请记住,某些数据库不支持 TIMESTAMP WITH TIME ZONEOracle 得知的列类型和 PostgreSQL数据库。例如,MySQL does not support it .你需要第二列。

  • 如果这些更改 Not Acceptable ,那么您需要返回 LocalDateTime并在所有层(包括数据库)中依赖固定/预定义的时区。通常为此使用UTC。

    处理 ZonedDateTime在 JSF 和 JPA 中
    使用时 ZonedDateTime用合适的 TIMESTAMP WITH TIME ZONE DB 列类型,使用下面的 JSF 转换器在 String 之间转换在 UI 和 ZonedDateTime 中在模型中。此转换器将查找 patternlocale来自父组件的属性。如果父组件本身不支持 patternlocale属性,只需将它们添加为 <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 之间进行转换在模型和 java.util.Calendar在 JDBC 中(体面的 JDBC 驱动程序将需要/将它用于 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());
    }

    }

    处理 LocalDateTime在 JSF 和 JPA
    使用基于 UTC 时 LocalDateTime使用适当的基于 UTC 的 TIMESTAMP (没有时区!)DB 列类型,使用下面的 JSF 转换器在 String 之间转换在 UI 和 LocalDateTime 中在模型中。此转换器将查找 pattern , timeZonelocale来自父组件的属性。如果父组件本身不支持 pattern , timeZone和/或 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 之间进行转换在模型和 java.sql.Timestamp在 JDBC 中(体面的 JDBC 驱动程序将需要/将它用于 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 ,您要么需要使用 <converter><converter-id>localDateTimeConverter 重新注册它在 faces-config.xml ,或更改注释如下
     @FacesConverter("localDateTimeConverter")
  • <p:calendar>没有 timeOnly="true"忽略 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>对于属性,您需要将它们作为带有 getter/setter 的 bean 类属性添加到转换器类中,并在 *.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>

    关于jsf - 如何在 p :calendar 中使用 java.time.ZonedDateTime/LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34883270/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com