在下面的代码中,我的"if"比较中出现了错误。消息说"isBefore(java.time.chrono.ChronoZonedDateTime<?>) in ChronoZonedDateTime cannot be applied to (java.time.LocalDate)
"。如何将本地日期转换为ChronoZonedDateTime
?
LocalDate taxBegin = tax.getBeginAt();
if(contract.getBeginAt().isBefore(taxBegin)){
//do something
}
我尝试像ChronoZonedDateTime.from(taxBegin)
一样包装但没有奏效,它给了我"DateTimeException: Unable to obtain ZoneId from TemporalAccessor: 2019-12-01 of type java.time.LocalDat
">
为了将ZonedDateTime
对象转换为LocalDate
,您可以使用toLocalDate()
方法。因此,以下代码应该适合您:
LocalDate taxBegin = tax.getBeginAt();
if(contract.getBeginAt().toLocalDate().isBefore(taxBegin)){
//do something
}
有关在ZonedDateTime
和LocalDate
之间进行转换的示例,请查看 https://howtodoinjava.com/java/date-time/localdate-zoneddatetime-conversion/。
您可以使用atStartOfDay(ZoneId(
即。
public static ZonedDateTime convertLocalDate(final LocalDate ld) {
return ld.atStartOfDay(ZoneId.systemDefault());
}
您可以使用ZoneId.systemDefault()
或ZoneOffset.UTC
。
文档指出:如果区域 ID 是区域偏移量,则结果始终具有午夜时间。
所以你的代码将是
if (contract.getBeginAt().isBefore(convertLocalDate(taxBegin))) {
//do something
}
如果要将其转换为特定时间,则应使用taxBegin.atTime(LocalTime).atZone(ZoneId)
.
如果你有LocalDateTime
而不是LocalDate
,它会很好用。但既然你LocalDate
,你就失去了时间。现在唯一的方法是将现有ChronoZonedDateTime
转换为LocalDate
并进行比较。但是,如果时区不同,这可能并不总是有效。
同一时区:
contract.getBeginAt().toLocalDate().isBefore(taxBegin)