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();
c1.setTime(f);
c2.setTime(l);
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 ?
Hope this might Help you
public int diffInWeeks(Date start, Date end) { long diffSeconds = (end.getTime() - start.getTime())/1000; return (int)diffSeconds/(60 * 60 * 24 * 7); }
It is pretty easy with joda time:
Joda Time computes weeks with durations of two dates which may not meet our requirements in some cases. I have a method with Joda Time to compute natural weeks between two dates. Hope it can help you. If you don't use Joda Time, you may modify the code with Calendar to do the same thing.
Updating answer to account for Java 8
You may do it the following way:
This should give you an int representing the number of weeks between the two dates.