Java中是否有Joda-Time间隔的替代方法,它可以用作结束时间
我正在尝试检查特定日期是否在特定日期范围内。我在 Java 中遇到了 Joda 时间间隔。但它作为结束时间独占。
那么是否有一种替代方法可以作为结束时间(包括结束时间)
回答
时间
我建议您使用现代 Date-Time API *。
下面引用的是Joda-Time 主页上的一个通知:
请注意,从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310) - 替代该项目的 JDK 的核心部分。
您可以使用!date.isAfterwheredate是对LocalDate 例如的引用
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2021, 5, 10);
LocalDate end = LocalDate.of(2021, 6, 10);
for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
// ...
}
}
}
从Trail: Date Time 中了解有关现代日期时间 API 的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目和您的 Android API 工作级别仍然不符合 Java-8,请检查通过 desugaring和How to use ThreeTenABP in Android Project可用的 Java 8+ APIs。
- Solid Answer. Further tip: The [`LocalDateRange`](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/LocalDateRange.html) class in the [*ThreeTen-Extra*](https://www.threeten.org/threeten-extra/) library has methods to treat the ending as inclusive, using "closed" terminology, as in full-closed versus half-open. But I recommend always working with half-open to keep your logic consistent. I have seen many miscommunications amongst businesspeople regarding fully-closed versus half-open. And, using half-open enables time spans that neatly abut.