Anton Smith Anton Smith - 2 years ago 204
Java Question

Get the number of weeks between two Dates.

Im working in a project and I got two types in Date. I want to calculate the number of weeks between these two dates. The dates can be in diffrent years. Is there any good solution for this?

I have tried to implemenent this with Joda-time which was suggested in other topics..

Im not familar with this library, but I tried to do something like this:

public static int getNumberOfWeeks(Date f, Date l){
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
DateTime start = new DateTime(c1.YEAR, c1.MONTH, c1.DAY_OF_MONTH, 0, 0, 0, 0);
DateTime end = new DateTime(c2.YEAR, c2.MONTH, c2.DAY_OF_MONTH, 0, 0, 0, 0);
Interval interval = new Interval(start, end);
Period p = interval.toPeriod();
return p.getWeeks();

But this is completely wrong... any suggestions ?

Answer Source

It is pretty easy with joda time:

DateTime dateTime1 = new DateTime(date1);
DateTime dateTime2 = new DateTime(date2);

int weeks = Weeks.weeksBetween(dateTime1, dateTime2).getWeeks();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download