6

年のすべての週に加えて、毎週の開始日と終了日を取得する方法はありますか? (ジョダタイム付き)

このようなもの(2012):

週: 21 開始: 21.05.2012 終了: 27.05.12

ご協力いただきありがとうございます

4

3 に答える 3

6

これを試して:

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

1 月 1 日は日曜日ではないため、週番号は 52 から始まり、1 から 51 まで続くことに注意してください。

代わりに、月曜日から日曜日の各週の日付を表示したい場合:

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);
}
于 2012-05-23T13:51:00.770 に答える
3
于 2017-07-10T04:03:46.323 に答える
1

Joda Time を使用したことはありません。私はこのようなことをします:

  1. 週番号と 2 つの DateTime (開始、終了) を持つクラスを作成します。
  2. このクラスのリストを作成します
  3. 1 年間 (週ごと) に繰り返し、現在の週をリストに保存します。

これは、標準の Java カレンダー API でこれを行う方法です。おそらく Joda Time の方が少し簡単でしょう。わかりません。

于 2012-05-23T13:41:19.630 に答える