我想找到两个日期之间的年数。我写了一个简单的测试用例来检查它。
@Test
public void testGetYears() {
DateTime oldDate = new DateTime(2014,1,1,0,0,0,0);
DateTime newDate = new DateTime(2016,2,1,0,0,0,0);
Days.daysBetween(oldDate, newDate).getDays(); //this line works
Years.yearsBetween(oldDate, newDate).getYears(); //no suitable method found
assertEquals(2, Years.yearsBetween(oldDate, newDate).getYears());
}
错误:
Error:(146, 14) java: no suitable method found for yearsBetween(org.elasticsearch.common.joda.time.DateTime,org.elasticsearch.common.joda.time.DateTime)
method org.joda.time.Years.yearsBetween(org.joda.time.ReadableInstant,org.joda.time.ReadableInstant) is not applicable
(argument mismatch; org.elasticsearch.common.joda.time.DateTime cannot be converted to org.joda.time.ReadableInstant)
method org.joda.time.Years.yearsBetween(org.joda.time.ReadablePartial,org.joda.time.ReadablePartial) is not applicable
(argument mismatch; org.elasticsearch.common.joda.time.DateTime cannot be converted to org.joda.time.ReadablePartial)
我已经查看了几年之间的定义是否需要与daysBetween函数中相同的参数。所以我想知道为什么它在多年之后不起作用。
我在这里遗漏了什么吗?
答案 0 :(得分:1)
您可以使用Period:
DateTime oldDate = new DateTime(2014,1,1,0,0,0,0);
DateTime newDate = new DateTime(2016,2,1,0,0,0,0);
Period p = new Period(oldDate, newDate);
int years = p.getYears();
检索两个日期之间的年份。
答案 1 :(得分:1)
您尝试使用elasticsearch(DateTime
)提供的org.elasticsearch.common.joda.time.DateTime
和Years
类joda-time本身(org.joda.time.Years
)。
要么到处使用joda-time类,要么使用elasticsearch提供的joda-time类;但不是两个在同一时间!