Joda Time - 获得一年中的所有周

问题描述 投票:6回答:3

有没有办法获得一周的所有周,加上每周的开始和结束日期? (使用Joda-Time

这样的事情(2012):

周:21开始:2012年5月21日结束:27.05.12

谢谢你的帮助

java jodatime date-arithmetic
3个回答
5
投票

试试这个:

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);
}

1
投票

从未使用过Joda Time。我会做这样的事情:

  1. 创建一个具有周数和两个DateTimes(开始,结束)的类
  2. 创建此类的列表
  3. 迭代一年(每周一周)并将当前周保存在列表中

这就是我用标准的java日历api做这个的方式。可能Joda Time有点容易,我不知道。


1
投票

Joda-Time is in maintenance mode

仅供参考,Joda-Time项目现在在maintenance mode,团队建议移民到java.time班。见Tutorial by Oracle

Define ‘week’

您可以通过不同方式定义一周。

我会假设你的意思是标准的ISO 8601 week。第1周是一年中的第一个星期四,从星期一开始,而以星期为基础的一年有52或53周。在日历年结束或开始的几天可以在另一个星期的年份登陆。

java.time

现代方法使用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 ) ;
}

About java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,如java.util.DateCalendarSimpleDateFormat

现在在Joda-Timemaintenance mode项目建议迁移到java.time班。

要了解更多信息,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规格是JSR 310

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。你可能会在这里找到一些有用的类,如IntervalYearWeekYearQuartermore

© www.soinside.com 2019 - 2024. All rights reserved.