java - 如何处理 LocalDate period. Between 结果?

标签 java android period localdate threetenbp

我使用 LocalDate (ThreeTenABP) 来计算给定日期之间的时间段。当我使用 01/01/2018 作为第一个日期,12/31/2018 作为第二个日期时,Period. Between 给出以下结果:

00 years
11 months
30 days

恕我直言,这是错误的,因为全年有 12 个月。 我尝试添加一天。然后我得到:

00 years
11 months
31 days

我需要一种可靠的方法来获取给定期间内完整月份的实际数量。

最佳答案

如果您查看 Javadoc Period.between() ,它告诉您结束日期是排他(意思是:不计算在内)。

The start date is included, but the end date is not. The period is calculated by removing complete months, then calculating the remaining number of days, adjusting to ensure that both have the same sign.

我编写了这段代码,它的功能似乎符合我的预期......

LocalDate d1 = LocalDate.of(2018, 1, 1);
LocalDate d2 = LocalDate.of(2018, 12, 31);
Period p1 = Period.between(d1, d2);
System.out.println(p1.getYears() + " years, " + p1.getMonths() + " months, " + p1.getDays() + " days");
// Prints: 0 years, 11 months, 30 days

添加一天,使其成为 2019-01-01,给我一年:

LocalDate d3 = LocalDate.of(2019, 1, 1);
Period p2 = Period.between(d1, d3);
System.out.println(p2.getYears() + " years, " + p2.getMonths() + " months, " + p2.getDays() + " days");    
// Prints: 1 years, 0 months, 0 days

编辑:

如果您只是向计算的 Period 对象添加一天,那么实际上只是添加一天,而不是像 Between 方法那样重新计算周期。以下是 Period 中执行 plusDays() 的代码:

public Period plusDays(long daysToAdd) {
    if (daysToAdd == 0) {
        return this;
    }
    return create(years, months, Math.toIntExact(Math.addExact(days, daysToAdd)));
}

如果您执行create 调用,它实际上只是向天数计数器添加一天,而不会重新计算任何内容。要正确地将一天添加到一个时间段中,请使用不同的端点重新计算它,如我上面所述。

关于java - 如何处理 LocalDate period. Between 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48359582/

相关文章:

java - Duration中的 'PT'前缀代表什么?

java - LinkedHashMap 具有访问内部链表的方法

java - 使用 Clojure/Java 为 X.Org 平台编写 WM 所需的技能和知识

java - 在android中退出应用程序时如何删除由createTempFile创建的所有临时文件?

android - 对 H264 NAL 流进行 fragment 整理(最初是 1722 avb 数据包)

java - 在另外两个textview获取值之后设置textview值

php - 如果在 PHP 字符串中间使用 'period' 字符 (.) 是什么意思?

java - 如何访问子类的变量?

java - 如何检索未知子项中未知键的值?

android - 获取对内部电话连接实例的引用