代码之家  ›  专栏  ›  技术社区  ›  Chayma Atallah

使用日历比较Java 7中的日期

  •  0
  • Chayma Atallah  · 技术社区  · 7 年前

    我比较了治疗的开始日期和结束日期,以检查其是否持续超过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);
    }
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   user7605325 user7605325    7 年前

    这个 Date 构造函数(例如您正在使用的构造函数: new Date(2017,1,1) 已弃用 误导 ,因为年份的索引为1900(因此2017年变为3917),月份的索引为零(数值范围为零(1月)到11(12月))。所以这并不像你想的那样:

    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 .

    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
    

    尽管 7月1日 终止


    旧阶级( 日期 , Calendar SimpleDateFormat )有 lots of problems design issues ,它们正被新的API所取代。

    在里面 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
    }