如何在Java中显示每月的几周

时间:2014-04-19 14:00:20

标签: android calendar jodatime

我试图计算一个月中的几周,但我很困惑,我该怎么办...(我使用Joda-Time

我考虑过,例如,当前月份(输入中的变量):

enter image description here

我希望在输出中看到这个结果(可能基于本地日期):

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

1 个答案:

答案 0 :(得分:1)

根据我在评论中发布的链接,以及关于plusDays和plusWeeks的提示,我发布了评论,我使用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 ) );

跑步时......

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

至于以不同方式格式化日期字符串,您可以在StackOverflow中搜索“joda格式”以查找许多示例。

要使用星期几以本地化方式开始本周,请参阅this question。但通常最好询问用户。而对于美国读者来说,请记住,美国在周日开始这一周是少数。