Week Between Two Dates Java + Joda Time

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

+4
source share
2 answers

JodaTime Weeks.weeksBetween (s, e) only returns an entire week. Incomplete weeks are not counted. To solve this problem, you must ensure that the days are at the beginning and at the end of the week. Try the following:

 int weeks = Weeks.weeksBetween(s.dayOfWeek().withMinimumValue().minusDays(1), e.dayOfWeek().withMaximumValue().plusDays(1)).getWeeks(); 

MinusDays / plusDays ensures that the weeks I'm trying to count are full.

The same logic applies to months:

 int months = Months.monthsBetween(s.dayOfMonth().withMinimumValue().minusDays(1), e.dayOfMonth().withMaximumValue().plusDays(1)).getMonths(); 
+6
source
  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 this give you what you need?

0
source

Source: https://habr.com/ru/post/1399515/


All Articles