试试这个:
SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Period weekPeriod = new Period().withWeeks(1);
DateTime startDate = new DateTime(2012, 1, 1, 0, 0, 0, 0 );
DateTime endDate = new DateTime(2013, 1, 1, 0, 0, 0, 0 );
Interval i = new Interval(startDate, weekPeriod );
while(i.getEnd().isBefore( endDate)) {
System.out.println( "week : " + i.getStart().getWeekOfWeekyear()
+ " start: " + df.format( i.getStart().toDate() )
+ " ending: " + df.format( i.getEnd().minusMillis(1).toDate()));
i = new Interval(i.getStart().plus(weekPeriod), weekPeriod);
}
请注意,周数从52开始,然后从1 - 51开始,因为1月1日不在星期日。
如果您想要查看每个星期一到星期日的日期:
SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Period weekPeriod = new Period().withWeeks(1);
DateTime startDate = new DateTime(2012, 1, 1, 0, 0, 0, 0 );
while(startDate.getDayOfWeek() != DateTimeConstants.MONDAY) {
startDate = startDate.plusDays(1);
}
DateTime endDate = new DateTime(2013, 1, 1, 0, 0, 0, 0);
Interval i = new Interval(startDate, weekPeriod);
while(i.getStart().isBefore(endDate)) {
System.out.println("week : " + i.getStart().getWeekOfWeekyear()
+ " start: " + df.format(i.getStart().toDate())
+ " ending: " + df.format(i.getEnd().minusMillis(1).toDate()));
i = new Interval(i.getStart().plus(weekPeriod), weekPeriod);
}
从未使用过Joda Time。我会做这样的事情:
这就是我用标准的java日历api做这个的方式。可能Joda Time有点容易,我不知道。
仅供参考,Joda-Time项目现在在maintenance mode,团队建议移民到java.time班。见Tutorial by Oracle。
您可以通过不同方式定义一周。
我会假设你的意思是标准的ISO 8601 week。第1周是一年中的第一个星期四,从星期一开始,而以星期为基础的一年有52或53周。在日历年结束或开始的几天可以在另一个星期的年份登陆。
现代方法使用java.time类,以及它们在ThreeTen-Extra项目中的扩展。
从ThreeTen-Extra,使用YearWeek
类。
YearWeek start = YearWeek.of( 2017 , 1 ) ; // First week of the week-based year 2017.
获得本周的52周或53周的周数。
int weeks = start.lengthOfYear() ;
…要么…
int weeks = ( start.is53WeekYear() ) ? 53 : 52 ;
循环一年中的每个星期。对于每个YearWeek
,要求它为该周的开始和结束生成一个LocalDate
。
List<String> results = new ArrayList<>( weeks ) ;
YearWeek yw = start ;
for( int i = 1 , i <] weeks , i ++ ) {
String message = "Week: " + yw + " | start: " + yw.atDay( DayOfWeek.MONDAY ) + " | stop: " + yw.atDay( DayOfWeek.SUNDAY ) ;
results.add( message ) ;
// Prepare for next loop.
yw = yw.plusWeeks( 1 ) ;
}
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,如java.util.Date
,Calendar
和SimpleDateFormat
。
现在在Joda-Time的maintenance mode项目建议迁移到java.time班。
要了解更多信息,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规格是JSR 310。
从哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。你可能会在这里找到一些有用的类,如Interval
,YearWeek
,YearQuarter
和more。