Вопрос

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
Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top