Ajinkya Pisal
Ajinkya Pisal

Reputation: 591

Can't convert DateTime to ReadableInstant using Joda time

I want to find the number of years between two dates. I wrote simple test case to check that.

@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:

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)

I have look into the yearsBetween definition is requires same parameter as in daysBetween function. So I am wondring why it does not work for yearsBetween.

Am I missing anything here?

Upvotes: 0

Views: 1789

Answers (2)

fge
fge

Reputation: 121780

You try and use DateTime as provided by elasticsearch (org.elasticsearch.common.joda.time.DateTime) with the Years class of joda-time itself (org.joda.time.Years).

Either use joda-time classes everywhere or elasticsearch provided joda-time classes; but not both at the same time!

Upvotes: 1

ParkerHalo
ParkerHalo

Reputation: 4430

You could use Period for that:

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();

retrieves the years between the two dates.

Upvotes: 1

Related Questions