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

Tin*_*iny 22 jsf timezone calendar primefaces java-time

我一直在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));
Run Code Online (Sandbox Code Playgroud)

当地时区比UTC/ 提前5小时30分钟GMT.因此,转换为UTC应从使用Joda Time正确发生的日期时间中扣除5小时30分钟.它按预期显示以下输出.

05-Jan-2016 09:34:44 AM +0000
Run Code Online (Sandbox Code Playgroud)

► 已+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));
Run Code Online (Sandbox Code Playgroud)

它意外地显示以下错误输出.

05-Jan-2016 03:04:44 PM +0000
Run Code Online (Sandbox Code Playgroud)

显然,转换的日期时间不符合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));
Run Code Online (Sandbox Code Playgroud)

反过来显示以下内容.

05-Jan-2016 09:34:44 AM Z
Run Code Online (Sandbox Code Playgroud)

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

时区完全透明地取决于用户的当前时区.

豆只有一个属性.

@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.
    }
}
Run Code Online (Sandbox Code Playgroud)

这将以意想不到的方式工作,如前三个代码片段中的倒数第二个示例/中间所示.

特别是,如果你进入05-Jan-2016 12:00:00 AM +0530,它会重新显示05-Jan-2016 05:30:00 AM IST,因为原来的转换05-Jan-2016 12:00:00 AM +0530UTC转换器中的失败.

转换从其偏移是当地时区+05:30UTC,然后从转换UTC回该时区显然必须重新显示为通过其是给定的转换器的基本的功能性的日历组件输入同一日期时间.


更新:

JPA的转换器,并从java.sql.Timestampjava.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 38

您的具体问题是您从Joda的无区域日期时间实例迁移DateTime到Java8的分区日期时间实例ZonedDateTime而不是Java8的无区域日期时间实例LocalDateTime.

使用ZonedDateTime(或OffsetDateTime)代替LocalDateTime至少需要2个额外的更改:

  1. 在日期时间转换期间,请勿强制使用时区(偏移).相反,在解析期间将使用输入字符串的时区(如果有),并且ZonedDateTime在格式化期间必须使用实例中存储的时区.

    DateTimeFormatter#withZone()将只会产生令人困惑的结果,ZonedDateTime因为它将在解析过程中作为后备(它仅在输入字符串或格式模式中不存在时区时使用),并且在格式化期间将充当覆盖(存储的时区ZonedDateTime完全被忽略) .这是您可观察到的问题的根本原因.withZone()在创建格式化程序时省略它应该修复它.

    请注意,当您指定转换器但没有指定转换器时timeOnly="true",则无需指定<p:calendar timeZone>.即使你这样做,你也更愿意使用TimeZone.getTimeZone(zonedDateTime.getZone())而不是硬编码.

  2. 您需要在所有层(包括数据库)上携带时区(偏移).但是,如果您的数据库具有"没有时区的日期时间"列类型,则在持久化期间时区信息会丢失,并且在从数据库返回时您将遇到麻烦.

    目前还不清楚您正在使用哪个数据库,但请记住,某些数据库不支持OraclePostgreSQL 数据库中TIMESTAMP WITH TIME ZONE已知的列类型.例如,MySQL不支持它.你需要第二列.

如果这些更改不可接受,那么您需要退回LocalDateTime并依赖所有层(包括数据库)中的固定/预定义时区.通常使用UTC.


与处理ZonedDateTime在JSF和JPA

使用ZonedDateTime适当的TIMESTAMP WITH TIME ZONEDB列类型时,请使用以下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();
    }

}
Run Code Online (Sandbox Code Playgroud)

并使用下面的JPA转换器ZonedDateTime在模型和java.util.CalendarJDBC中进行转换(体面的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());
    }

}
Run Code Online (Sandbox Code Playgroud)

与处理LocalDateTime在JSF和JPA

当使用基于LocalDateTime适当的UTC TIMESTAMP(没有时区!)DB列类型的UTC 时,使用下面的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;
    }

}
Run Code Online (Sandbox Code Playgroud)

并使用下面的JPA转换器LocalDateTime在模型和java.sql.TimestampJDBC中进行转换(体面的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();
    }

}
Run Code Online (Sandbox Code Playgroud)

适用LocalDateTimeConverter于您的具体案例<p:calendar>

你需要改变以下内容:

  1. 由于<p:calendar>不查找转换器forClass,您需要使用<converter><converter-id>localDateTimeConverterin 重新注册它faces-config.xml,或者更改注释,如下所示

    @FacesConverter("localDateTimeConverter")
    
    Run Code Online (Sandbox Code Playgroud)
  2. 由于<p:calendar>timeOnly="true"忽略timeZone,并在弹出窗口中提供编辑它的选项,您需要删除该timeZone属性以避免转换器混淆(仅当时区不存在时才需要此属性pattern).

  3. 您需要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>
Run Code Online (Sandbox Code Playgroud)

如果您打算<my:convertLocalDateTime>使用属性创建自己的属性,则需要将它们作为类似bean的属性与getter/setter一起添加到转换器类并注册它,*.taglib.xml如本答案所示:使用属性为Converter创建自定义标记

<h:outputText id="display" value="#{bean.dateTime}">
    <my:convertLocalDateTime pattern="dd-MMM-yyyy hh:mm:ss a Z" 
                             timeZone="Asia/Kolkata" />
</h:outputText>
Run Code Online (Sandbox Code Playgroud)

  • 这是工作.谢谢.答案至少应该得到一笔赏金,因为它耗费了相当多的时间.我明天会开始赏金. (3认同)
  • @Gilberto:JSF 2.3 将通过`f:convertDateTime` 提供内置支持。 (2认同)