【问题标题】:Comparing Dates in Java 7 using Calendar使用日历比较 Java 7 中的日期
【发布时间】:2018-02-03 04:59:47
【问题描述】:

我正在比较治疗的开始日期和结束日期,以检查它是否持续超过 6 个月。如果该期间不包括 2 月,那么一切都很好,但是如果我将 1 月 1 日与 6 月 30 日进行比较,则会引发我的异常。为了比较这两个时期,我将开始日期添加 6 个月并将结果与​​结束日期进行比较,如下所示:

Date start = new Date(2017,1,1);
Date end = new Date(2017,6,30);

Calendar startOfTreatment = new Calendar.getInstance();
startOfTreatment.setTime(start);

Calendar endOfTreatment = new Calendar.getInstance();
endOfTreatment.setTime(end);

startOfTreatment.add(Calendar.MONTH, 6);
if (startOfTreatment.compareTo(endOfTreatment) > 0) {
    throw new InfinishedTreatmentException(startOfTreatment,endOfTreatment);
}

我该如何解决这个问题?

【问题讨论】:

  • 可能值得发布更多代码,例如 startOfTreatment 的填充方式 - 它是实际日期吗?一年?
  • 我添加了我正在使用的测试
  • 2 月 1 日之后的六个月是 8 月 1 日,实际上是晚于 7 月 30 日。这不符合您的预期吗?
  • 即使我在 7 月 1 日测试时也没有同样的问题

标签: calendar java-7 java-time date-comparison


【解决方案1】:

Date 构造函数(例如您正在使用的构造函数:new Date(2017,1,1))不仅已弃用(因此您应该避免使用它们)而且还误导,因为年份索引为 1900(所以 2017 变为 3917),月份索引为零(值在零(一月)到 11(十二月)的范围内)。所以这并不像你想象的那样:

Date start = new Date(2017, 1, 1); // February 1st 3917
Date end = new Date(2017, 6, 30); // July 30th 3917

当您将 6 个月添加到 start 时,它变为 8 月 1 日st,在 end 之后。

要创建 1 月 1 日st 和 6 月 30 日th,您必须使用 month - 1 并且要拥有 2017 年,您必须使用 117(2017 - 1900):

Date start = new Date(117, 0, 1); // January 1st 2017
Date end = new Date(117, 5, 30); // June 30th 2017

尽管如此,start 加上 6 个月将是 7 月 1 日st,它仍然在 end 之后(因此您的代码会抛出异常)。


旧的类(DateCalendarSimpleDateFormat)有 lots of problemsdesign issues,它们正在被新的 API 取代。

Java 中,您可以使用 ThreeTen Backport,这是 Java 8 新日期/时间类的一个很好的向后移植。

这个新的 API 有lots of new date and time types 来处理不同的情况。由于我们只处理日期(日/月/年),我们可以使用org.threeten.bp.LocalDate

LocalDate start = LocalDate.of(2017, 1, 1); // January 1st 2017
LocalDate end = LocalDate.of(2017, 6, 30); // June 30th 2017

// 6 months after start
LocalDate sixMonthsLater = start.plusMonths(6);
if (sixMonthsLater.isAfter(end)) {
    // throw exception
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多