简体   繁体   English

获取两个日期之间的天数

[英]Get a Period of Days between two Dates

I use java.time.Period#getDays() to get the number of days for a given period of LocalDate s.我使用java.time.Period#getDays()来获取给定时间段的LocalDate的天数。

It seems to work for most cases, but for a whole month, I get a period of zero days.它似乎适用于大多数情况,但整整一个月,我都有零天的时间。

The following test case fails ( java.lang.AssertionError: expected:<30> but was:<0> ):以下测试用例失败( java.lang.AssertionError: expected:<30> but was:<0> ):

@Test
public void testOneMonthPeriodDays() {
    Period p = Period.between(LocalDate.of(2017, 06, 01), LocalDate.of(2017, 07, 01));
    assertEquals(30, p.getDays());
}

I believe this is the correct result.我相信这是正确的结果。 If you run the following test you will see that getMonths() returns 1. It seems that getDays is not get the total days but get the remainder days.如果您运行以下测试,您将看到 getMonths() 返回 1。似乎 getDays 不是获取总天数,而是获取剩余天数。

@Test
public void testOneMonthPeriodDays() {
    Period p = Period.between(LocalDate.of(2017, 06, 01), LocalDate.of(2017, 07, 01));
    assertEquals(0, p.getDays());
    assertEquals(1, p.getMonths());
}

To get the total number of days between two dates see this question Calculate days between two dates in Java 8要获得两个日期之间的总天数,请参阅此问题计算 Java 8 中两个日期之间的天数

To quote the answer given in that question:引用该问题中给出的答案:

LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);

Note that DAYS is member of java.time.temporal.ChronoUnit enum.请注意, DAYSjava.time.temporal.ChronoUnit枚举的成员。

JavaDoc for java.time.Period#getDays() says: java.time.Period#getDays() JavaDoc 说:

returns the amount of days of this period, may be negative返回此期间的天数,可能为负数

I guess this is missleading and it does not really return the total amount of days.我想这是误导,它并没有真正返回总天数。

I use now我现在用

final long daysElapsed = ChronoUnit.DAYS.between(LocalDate.of(2017, 06, 01), LocalDate.of(2017, 07, 01));

which works as expected.它按预期工作。

Do the following:请执行下列操作:

long daysDifference = DAYS.between(dayInitial, dayAfter);

where:在哪里:

LocalDate dateInitial;   //initial date
LocalDate dateAfter;      //later date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM