gpt4 book ai didi

android - Java如何显示一个月中的星期几

转载 作者:行者123 更新时间:2023-11-30 02:56:30 25 4
gpt4 key购买 nike

我正在尝试计算一个月中的几周,但我很困惑我该怎么做...(我正在使用 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

最佳答案

按照我在评论中发布的链接,以及我作为评论发布的关于 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 .但通常最好询问用户。对于美国读者,请记住美国是周日开始一周的少数人。

关于android - Java如何显示一个月中的星期几,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23170994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com