java - JodaTime 给出的错误结果

标签 java jodatime

请问我想计算两个日期之间的时间段,我搜索了但没有找到我需要的。我有这个代码:

public int getNbjours() {
        DateTime dt1 = new DateTime(date1);
        DateTime dt2 = new DateTime(date2);
        Period period = new Period(dt1, dt2);
        nbjours=period.getDays();   
           return nbjours;
    }


    public int getNbmois() {
        DateTime dt1 = new DateTime(date1);
        DateTime dt2 = new DateTime(date2);
        Period period = new Period(dt1, dt2);
         nbmois=period.getMonths();

        return nbmois;
    }

问题是有时它会给我错误的结果,例如:

From 2013-05-27 To 2013-06-28 => 1 day and 1 months (it's right here)
From 2013-05-27 To 2013-07-26 => 1 it gives me also 1 day and 1 months and that's false !
From 2013-04-01 To 2013-09-04 => 3 days and 5 months (here it's right)

在该错误值中,通常 27/0526/07 实际上是 1 个月,但不仅仅是 1 天29 天 请问为什么它给我错误的值?

最佳答案

org.joda.time.Period 的行为似乎是错误的,因为您错过了几周。请参阅此测试:

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.joda.time.DateMidnight;
import org.joda.time.Period;
import org.junit.Test;

public class DateTimePeriodTest {

    @Test
    public void period1ShouldHaveNoWeeks() {
        final Period period = new Period(new DateMidnight(2013, 5, 27), new DateMidnight(2013, 6, 28));
        assertThat(period.getMonths(), is(1));
        assertThat(period.getWeeks(), is(0));
        assertThat(period.getDays(), is(1));
    }

    @Test
    public void period2ShouldHaveFourWeeks() {
        final Period period = new Period(new DateMidnight(2013, 5, 27), new DateMidnight(2013, 7, 26));
        assertThat(period.getMonths(), is(1));
        assertThat(period.getWeeks(), is(4));
        assertThat(period.getDays(), is(1));
    }
}

祝你好运!

关于java - JodaTime 给出的错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16999345/

相关文章:

java - ListView 和线程安全的自定义适配器

java - 有没有办法知道是否有CDI事件的观察者?

java - 为什么使用 java.io.Console?

java - 带有适当数字后缀的 Joda DateTimeFormat

java - 如何提取属于特定时间范围的joda DateTime?

java - 通过java在MySql中存储字符串数组?

java - DateTimeFormatter.parseLocalDate 抛出 UnsupportedOperationException

java - java Date 和 LocalDateTime 中一个月的天数

java - joda-time 解析日期和时间中的解析异常

java - Selenium -Java : Microsoft Edge automation browser (Windows 10)