1

I'm trying to calculate the weeks of the month but I'm very confused how can I do... (I'm using Joda-Time)

I considered, for example, current month (variable in input):

enter image description here

I would like see in output this result (based on Local date, possibly):

1 week: 03-30-2014 --- 04-05-2014
2 week: 04-06-2014 --- 04-12-2014
3 week: 04-13-2014 --- 04-19-2014
4 week: 04-20-2014 --- 04-26-2014
5 week: 04-27-2014 --- 05-03-2014
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
user3449772
  • 749
  • 1
  • 14
  • 27
  • possible duplicate of [Joda Time: First day of week?](http://stackoverflow.com/questions/1801907/joda-time-first-day-of-week) – Basil Bourque Apr 19 '14 at 15:50
  • Get a DateTime object then call the `plusDays` or `plusWeeks` methods. Many examples on StackOverflow if you search. – Basil Bourque Apr 19 '14 at 15:52
  • Is not same case because I need to manage the previus month and the next month... – user3449772 Apr 19 '14 at 17:45
  • 1
    No solution with JodaTime when it comes to localized week calculations. You have to roll your own home-grown and possibly error-prone solution. Other libraries like JSR-310 in Java-8 are better (there watch out for class `WeekFields`). – Meno Hochschild Apr 19 '14 at 20:46

1 Answers1

1

Following the link I posted in a comment, and the tip about plusDays and plusWeeks I posted as a comment, I wrote the following example using Joda-Time 2.3.

int month = DateTimeConstants.APRIL;
int year = 2014;
int dayOfWeek = DateTimeConstants.SUNDAY;

LocalDate firstOfMonth = new LocalDate( year, month, 1 );
LocalDate firstOfNextMonth = firstOfMonth.plusMonths( 1 );
LocalDate firstDateInGrid = firstOfMonth.withDayOfWeek( dayOfWeek );
if ( firstDateInGrid.isAfter( firstOfMonth ) ) { // If getting the next start of week instead of desired week's start, adjust backwards.
    firstDateInGrid = firstDateInGrid.minusWeeks( 1 );
}

LocalDate weekStart = firstDateInGrid;
LocalDate weekStop = null;
int weekNumber = 0;

do {
    weekNumber = weekNumber + 1;
    weekStop = weekStart.plusDays( 6 );
    System.out.println( weekNumber + " week: " + weekStart + " --- " + weekStop );  // 1 week: 03-30-2014 --- 04-05-2014
    weekStart = weekStop.plusDays( 1 );
} while ( weekStop.isBefore( firstOfNextMonth ) );

When run…

1 week: 2014-03-30 --- 2014-04-05
2 week: 2014-04-06 --- 2014-04-12
3 week: 2014-04-13 --- 2014-04-19
4 week: 2014-04-20 --- 2014-04-26
5 week: 2014-04-27 --- 2014-05-03

As for formatting the date string differently, you can search StackOverflow for "joda format" to find many examples.

To use a day-of-week to start the week in a localized manner, see this question. But generally it may be best to ask the user. And for the American readers, remember that the United States is in the minority with starting the week on Sunday.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154