Reputation: 14175
I wanted to get the number of weeks and months between two date range in Java. For ex., Start Date: 03/01/2012 End Date: 03/05/2012
Since the two dates fall in two different weeks I want the result to be 2 instead of 0.
Second part of the problem is: Start Date: 02/29/2012 End Date: 03/01/2012
Number of months in between should be 2.
I have been searching online regarding this and lot of people have recommended using Joda Date time in Java. So I gave it a shot. I was able to get the weeks working but I am not sure if this is the right way. Here is what I am doing to get the week duration:
DateTime s = new DateTime(Long.parseLong("1330573027000")); // 2012-02-29
DateTime e = new DateTime(Long.parseLong("1331005027000")); // 2012-03-05
Weeks weeks = Weeks.weeksBetween(s, e).plus(1);
This returns 1, when I am expecting 2 since two dates are in different weeks.
For months duration I tried to follow the same but it returns 0 but I want it to return 2 since the two dates are in two different months.
Could someone please point me in right direction?
Thanks!
Edit: I think I got one way of doing it, please let me know if it looks right:
DateTime start = new DateTime(Long.parseLong("1330659427000"));
DateTime start = new DateTime(Long.parseLong("1331005027000"));
DateTime finalStart = start.dayOfWeek().withMinimumValue();
DateTime finalEnd = end.dayOfWeek().withMaximumValue();
And then get the difference between finalStart and finalEnd. Does this looks correct?
Edit2 Updated the end time
Upvotes: 4
Views: 8600
Reputation: 420
JodaTime Weeks.weeksBetween(s, e) returns only whole week count. Incomplete weeks are not counted. To resolve this, you must garantee that the days are at the start and at the end of the week. Try this:
int weeks = Weeks.weeksBetween(s.dayOfWeek().withMinimumValue().minusDays(1),
e.dayOfWeek().withMaximumValue().plusDays(1)).getWeeks();
The minusDays/plusDays will garantee that the weeks i'm trying to count are full.
Same logic apply for Months:
int months = Months.monthsBetween(s.dayOfMonth().withMinimumValue().minusDays(1),
e.dayOfMonth().withMaximumValue().plusDays(1)).getMonths();
Upvotes: 7
Reputation: 6241
int OFFSET_ONE = 1;
DateTime t1 = new DateTime().withDate(2012, 02, 29).withDayOfWeek(1);
DateTime t2 = new DateTime().withDate(2012, 03, 05).withDayOfWeek(7);
int week1 = t2.weekOfWeekyear().get();
int week2 = t1.weekOfWeekyear().get();
System.out.println(week1-week2+OFFSET_ONE); // add OFFSET_ONE
does it give what you are after?
Upvotes: 0