I wanted to get the number of weeks and months between two date ranges in Java. For example, Start date: 03/01/2012 End date: 03/05/2012
Since two dates fall in two different weeks, I want the result to be 2 instead of 0.
The second part of the problem: Start date: 02/29/2012 End date: 03/01/2012
The number of months between them should be 2.
I searched online about this, and many people recommended using Joda Date time in Java. So I gave him a chance. I managed to work for a week, but I'm not sure if this is the right way. Here is what I do to get the duration of the week:
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 expect 2, as the two dates are in different weeks.
For several months, 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.
Can someone point me in the right direction?
Thanks!
Edit: I think I have one way to do this, 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 look right?
Edit2 Updated End Time