大多数情况下,这两种方法是相反的:
> Temporal Temporal.plus(long,TemporalUnit)
> long Temporal.until(Temporal,TemporalUnit)
例如从1-JAN开始:
System.out.println("1-JAN plus 1 month: " +
LocalDate.of(2017, 1, 1).plus(1, ChronoUnit.MONTHS));
System.out.println("1-JAN until 1-FEB in months: " +
LocalDate.of(2017, 1, 1).until(LocalDate.of(2017, 2, 1), ChronoUnit.MONTHS));
它们彼此相反:
1-JAN plus 1 month: 2017-02-01
1-JAN until 1-FEB in months: 1 // GOOD
但是,在这个例子中从31-JAN开始:
System.out.println("31-JAN plus 1 month: " +
LocalDate.of(2017, 1, 31).plus(1, ChronoUnit.MONTHS));
System.out.println("31-JAN until 28-FEB in months: " +
LocalDate.of(2017, 1, 31).until(LocalDate.of(2017, 2, 28), ChronoUnit.MONTHS));
它们不是彼此相反的:
31-JAN plus 1 month: 2017-02-28 // Bad? Should ceil to 1 March?
31-JAN until 28-FEB in months: 0 // Or is this bad? Should be 1?
我如何让他们成为彼此逆?
最佳答案 这些日期之间只有28天,所以整月的数量为0.但是,如果你想要少于1个月被认为是一个月,你可以使用一些舍入.例如
// compare the months after rounding to the next month
LocalDate a = LocalDate.of(2017, 1, 31);
LocalDate b = LocalDate.of(2017, 2, 28);
long months = a.plus(1, ChronoUnit.MONTHS)
.until(b.plus(1, ChronoUnit.MONTHS), ChronoUnit.MONTHS);
System.out.println(a + " until " + b + " in months: " + months);
版画
2017-01-31 until 2017-02-28 in months: 1
和
// compare the months after rounding to the next month
LocalDate a = LocalDate.of(2017, 1, 31);
LocalDate b = LocalDate.of(2017, 3, 30);
long months = a.plus(1, ChronoUnit.MONTHS)
.until(b.plus(1, ChronoUnit.MONTHS), ChronoUnit.MONTHS);
System.out.println(a + " until " + b + " in months: " + months);
版画
2017-01-31 until 2017-03-30 in months: 2
I probably want the plus to ceil instead of to floor
根据您的要求,您可能希望将所有月份视为理想的30天.