11

特定の日付の週の最後の週と最初の週を取得したい。たとえば、日付が 2011 年 10 月 12 日の場合、2011 年 10 月 10 日 (週の開始日として) と 2011 年 10 月 16 日 (週の終了日として) の日付が必要です。クラス (java.util.Calendar) ありがとうございます!

4

5 に答える 5

35

Calendarオブジェクトでそれを行う方法のコード。joda time ライブラリについても言及する必要があります。これは、多くのDate/Calendar問題を解決するのに役立ちます。

コード

public static void main(String[] args) {

    // set the date
    Calendar cal = Calendar.getInstance();
    cal.set(2011, 10 - 1, 12);

    // "calculate" the start date of the week
    Calendar first = (Calendar) cal.clone();
    first.add(Calendar.DAY_OF_WEEK, 
              first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));

    // and add six days to the end date
    Calendar last = (Calendar) first.clone();
    last.add(Calendar.DAY_OF_YEAR, 6);

    // print the result
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(df.format(first.getTime()) + " -> " + 
                       df.format(last.getTime()));
}
于 2011-10-04T08:39:52.537 に答える
1

サンプルコードはこちら

public static void main(String[] args) {

    Calendar cal = Calendar.getInstance();
    cal.set(2016, 2, 15);

    {
        Calendar startCal = Calendar.getInstance();
        startCal.setTimeInMillis(cal.getTimeInMillis());

        int dayOfWeek = startCal.get(Calendar.DAY_OF_WEEK);
        startCal.set(Calendar.DAY_OF_MONTH,
                (startCal.get(Calendar.DAY_OF_MONTH) - dayOfWeek) + 1);

        System.out.println("end date : " + startCal.getTime());
    }

    {
        Calendar endCal = Calendar.getInstance();
        endCal.setTimeInMillis(cal.getTimeInMillis());

        int dayOfWeek = endCal.get(Calendar.DAY_OF_WEEK);
        endCal.set(Calendar.DAY_OF_MONTH, endCal.get(Calendar.DAY_OF_MONTH)
                + (7 - dayOfWeek));

        System.out.println("start date : " + endCal.getTime());

    }
}

どちらが印刷されますか

start date : Sun Mar 13 20:30:30 IST 2016
end date : Sat Mar 19 20:30:30 IST 2016
于 2016-03-19T15:01:20.560 に答える
1

すべての日付が必要な場合

first.add(Calendar.DAY_OF_WEEK,first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK)); 

for (int i = 1; i <= 7; i++) {
    System.out.println( i+" Day Of that Week is",""+first.getTime());
    first.add(Calendar.DAY_OF_WEEK,1);
}
于 2013-03-21T09:35:26.257 に答える