gpt4 book ai didi

jpa - 如何将 java.util.Date 转换为 Java8 java.time.YearMonth

转载 作者:行者123 更新时间:2023-12-03 23:32:02 27 4
gpt4 key购买 nike

我怎样才能最好地转换 java.util.Date到 Java 8 java.time.YearMonth ?

不幸的是,以下抛出 DateTimeException :

YearMonth yearMonth = YearMonth.from(date.toInstant());

结果是:
java.time.DateTimeException: Unable to obtain YearMonth from TemporalAccessor: 2015-01-08T14:28:39.183Z of type java.time.Instant
at java.time.YearMonth.from(YearMonth.java:264)
...

我需要这个功能,因为我想存储 YearMonth使用 JPA 的数据库中的值。目前 JPA 不支持 YearMonth 's,所以我想出了以下 YearMonthConverter(省略了导入):
// TODO (future): delete when next version of JPA (i.e. Java 9?) supports YearMonth. See https://java.net/jira/browse/JPA_SPEC-63
@Converter(autoApply = true)
public class YearMonthConverter implements AttributeConverter<YearMonth, Date> {

@Override
public Date convertToDatabaseColumn(YearMonth attribute) {
// uses default zone since in the end only dates are needed
return attribute == null ? null : Date.from(attribute.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
}

@Override
public YearMonth convertToEntityAttribute(Date dbData) {
// TODO: check if Date -> YearMonth can't be done in a better way
if (dbData == null) return null;
Calendar calendar = Calendar.getInstance();
calendar.setTime(dbData);
return YearMonth.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
}
}

没有更好(更干净、更短)的解决方案(双向)吗?

最佳答案

简答:

// From Date to YearMonth
YearMonth yearMonth =
YearMonth.from(date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate());

// From YearMonth to Date
// The same as the OP:s answer
final Date convertedFromYearMonth =
Date.from(yearMonth.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());

说明:

YearMonth.from(TemporalAccessor)的JavaDoc -方法说:

The conversion extracts the YEAR and MONTH_OF_YEAR fields. The extraction is only permitted if the temporal object has an ISO chronology, or can be converted to a LocalDate.



因此,您需要能够:
  • 提取 YEARMONTH_OF_YEAR字段,或
  • 你应该使用可以转换为 LocalDate 的东西.

  • 让我们试试吧!
    final Date date = new Date();
    final Instant instant = date.toInstant();
    instant.get(ChronoField.YEAR); // causes an error

    这是不可能的,抛出异常:

    java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year at java.time.Instant.get(Instant.java:571) ...



    这意味着备选方案 1 已被排除在外。在这个关于 how to convert Date to LocalDate 的优秀回答中解释了原因。 .

    Despite its name, java.util.Date represents an instant on the time-line, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).

    The equivalent class to java.util.Date in JSR-310 is Instant, thus there is a convenient method toInstant() to provide the conversion.



    所以,一个 Date可以转换为 Instant但这对我们没有帮助,是吗?

    然而,方案 2 证明是成功的。转换 InstantLocalDate然后使用 YearMonth.from(TemporalAccessor) -方法。
        Date date = new Date();

    LocalDate localDate = date.toInstant()
    .atZone(ZoneId.systemDefault())
    .toLocalDate();

    YearMonth yearMonth = YearMonth.from(localDate);
    System.out.println("YearMonth: " + yearMonth);

    输出是(因为代码是在 2015 年 1 月执行的;):

    YearMonth: 2015-01

    关于jpa - 如何将 java.util.Date 转换为 Java8 java.time.YearMonth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27843156/

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