user3093402
user3093402

Reputation: 1469

Add months to days using joda-time

I need to create a method that takes a number of days and a number of months, add the two, and then returns the resulting number of days.

public int addMonthsToDays(int months, int days);//interface

I think of using joda DateTime, but there is no method for getting the total days. Here is an example implementation:

public int addMonthsToDays(int months, int days){
    DateTime dateTime = new DateTime().plusDays(days).plusMonths(months);
  return // what do I return?
}

Additional Note

I know some people will misread the above and come out with a number of questions, so in anticipation:

Upvotes: 2

Views: 1792

Answers (1)

Nanne
Nanne

Reputation: 64429

the problem is that you are working with dates, but actually want days. What you can do is make a new DateTime for today, and a different one with your added days/months, and then just calculate the difference in days.

in joda-time speak:

Days.between(startDate, endDate);

complete (untested) example would look like

public int addMonthsToDays(int months, int days){
  DateTime startDate = new DateTime();
  DateTime endDate = new DateTime().plusDays(days).plusMonths(months);
  return Days.between(startDate,endDate);
}

Upvotes: 5

Related Questions