-->

在Java中使用7日历日期比较(Comparing Dates in Java 7 using Ca

2019-10-28 14:34发布

我是一个treatement的开始日期比较它的最终检查,如果它持续超过6个月。 如果期间不包括二月份的一切都很好,但如果我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);
}

我怎样才能解决这个问题?

Answer 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 ,这是后end

要创建1月1 和6月30 ,你必须使用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 ,这仍然是后end (所以你的代码会抛出异常)。


老班( DateCalendarSimpleDateFormat )有很多问题和设计问题 ,他们正在被新的API取代。

Java <= 7,可以使用ThreeTen反向移植 ,对Java 8的新的日期/时间类有很大反向移植。

这个新的API有很多新的日期和时间类型来处理不同的情况。 正如我们与日期(日/月/年)只处理,我们可以使用一个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
}


文章来源: Comparing Dates in Java 7 using Calendar