如何将java.util.Date转换为Java8 java.time.YearMonth [英] How to convert java.util.Date to Java8 java.time.YearMonth
问题描述
如何才能最好地将 java.util.Date
转换为Java 8 java.time.YearMonth
?
How can I best convert a java.util.Date
to a Java 8 java.time.YearMonth
?
不幸的是,以下内容抛出 DateTimeException
:
Unfortunately the following throws a 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)
...
我需要此功能,因为我想存储使用JPA的数据库中的 YearMonth
值。目前JPA不支持 YearMonth
,所以我想出了以下YearMonthConverter(省略了导入):
I need this functionality since I want to store YearMonth
values in a database using JPA. Currently JPA does not support YearMonth
's, so I've come up with the following YearMonthConverter (imports omitted):
// 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);
}
}
不是更好(更干净,更短)解决方案(两个方向)?
Isn't there a better (cleaner, shorter) solution (for both directions)?
推荐答案
简答:
// 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) - 方法说:
转换提取YEAR和MONTH_OF_YEAR字段。仅当时态对象具有ISO年表或者可以转换为LocalDate时才允许提取。
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.
所以,你需要能够:
- 提取
年
和MONTH_OF_YEAR
字段,或 - 您应该使用可以转换为
LocalDate
的内容。
- extract the
YEAR
andMONTH_OF_YEAR
fields, or - you should use something that can be converted to a
LocalDate
.
试试吧!
final Date date = new Date();
final Instant instant = date.toInstant();
instant.get(ChronoField.YEAR); // causes an error
这是不可能的,抛出异常:
This is not possible, an exception is thrown:
java.time.temporal.UnsupportedTemporalTypeException:不支持的字段:年份
at java.time.Instant.get(Instant.java:571)
...
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year at java.time.Instant.get(Instant.java:571) ...
这意味着替代1会消失。有关如何将日期转换为LocalDate的优秀答案中解释了原因。
This means that alternative 1 goes out the window. The reason for is explained in this excellent answer about how to convert Date to LocalDate.
尽管名称如此,
java.util.Date
表示当时的瞬间-line,而不是日期。存储在对象中的实际数据是自1970-01-01T00:00Z(格林威治标准时间1970 /格林威治标准时间1970年初午夜)以来的长毫秒数。
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).
等效物JSR-310中的class to java.util.Date
是Instant,因此有一个方便的方法toInstant()来提供转换。
The equivalent class to java.util.Date
in JSR-310 is Instant, thus there is a convenient method toInstant() to provide the conversion.
因此,日期
可以转换为 Instant
但这对我们没有帮助,是吗?
So, a Date
can be converted to an Instant
but that did not help us, did it?
备选方案2证明是成功的。将 Instant
转换为 LocalDate
,然后使用 YearMonth.from(TemporalAccessor)
-method。
Alternative 2 however proves to be successful. Convert the Instant
to a LocalDate
and then use the YearMonth.from(TemporalAccessor)
-method.
Date date = new Date();
LocalDate localDate = date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
YearMonth yearMonth = YearMonth.from(localDate);
System.out.println("YearMonth: " + yearMonth);
输出为(因为代码于2015年1月执行;):
The output is (since the code was executed in January 2015 ;):
YearMonth:2015-01
YearMonth: 2015-01
这篇关于如何将java.util.Date转换为Java8 java.time.YearMonth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!