0

1か月の火曜日の数を計算する方法は?

を使用しcalender.setて特定の月を設定できます。その後、その月の月曜日、火曜日などの数を計算するにはどうすればよいですか。

コードは:

public static void main(String[] args )
{
    Calendar calendar = Calendar.getInstance();
    int  month = calendar.MAY; 
    int year = 2012;
    int date = 1 ;

    calendar.set(year, month, date);

    int MaxDay = calendar.getActualMaximum(calendar.DAY_OF_MONTH);
    int mon=0;

    for(int i = 1 ; i < MaxDay ; i++)
    {        
        calendar.set(Calendar.DAY_OF_MONTH, i);
        if (calendar.get(Calendar.DAY_OF_WEEK) == calendar.MONDAY ) 
            mon++;      
    }

    System.out.println("days  : " + MaxDay);    
    System.out.println("MOndays  :" + mon);
}
4

4 に答える 4

8

ここにコード全体を書かなくても、一般的な考え方は次のとおりです。

    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, Calendar.MAY); // may is just an example
    c.set(Calendar.YEAR, 2012);
    int th = 0;
    int maxDayInMonth = c.getMaximum(Calendar.MONTH);
    for (int d = 1;  d <= maxDayInMonth;  d++) {
        c.set(Calendar.DAY_OF_MONTH, d);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        if (Calendar.THURSDAY == dayOfWeek) {
            th++;
        }
    }

このコードは、木曜日の数をカウントする必要があります。すべての曜日をカウントするように変更できると思います。

明らかに、このコードは効率的ではありません。月のすべての日に繰り返します。最初の日の曜日、月の日数を取得するだけで最適化でき、(私は信じています)月全体を反復せずに各曜日の数を計算するコードを書くことができます。

于 2012-05-03T09:51:42.000 に答える
0

AlexR は、より効率的なバージョンについて言及しました。私はそれを回転させると思った:

private int getNumThursdays() {
    // create instance of Gregorian calendar 
    Calendar gc = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US);
    int currentWeekday = gc.get(Calendar.DAY_OF_WEEK);

    // get number of days left in month
    int daysLeft = gc.getActualMaximum(Calendar.DAY_OF_MONTH) - 
            gc.get(Calendar.DAY_OF_MONTH);

    // move to closest thursday (either today or ahead)
    while(currentWeekday != Calendar.THURSDAY) {
        if (currentWeekday < 7)  currentWeekday++;
        else currentWeekday = 1;
        daysLeft--;
    }

    // calculate the number of Thursdays left
    return daysLeft / 7 + 1;
}

注:現在の年、月、日などを取得する場合は、環境に依存します。たとえば、誰かが自分の電話の時刻を手動で間違った値に設定した場合、この計算は間違っている可能性があります。正確性を確保するには、信頼できるソースから現在の月、年、日、時刻に関するデータを取得することをお勧めします。

于 2014-02-13T19:22:45.037 に答える
0

Javaカレンダーには実際にそのためのプロパティが組み込まれていますCalendar.DAY_OF_WEEK_IN_MONTH

Calendar calendar = Calendar.getInstance(); //get instance
calendar.set(Calendar.DAY_OF_WEEK, 3);  //make it be a Tuesday (crucial)
//optionally set the month you want here
calendar.set(Calendar.MONTH, 4) //May
calendar.getActualMaximum(Calendar.DAY_OF_WEEK_IN_MONTH); //for this month (what you want)
calendar.getMaximum(Calendar.DAY_OF_WEEK_IN_MONTH); //for any month (not so useful)
于 2015-05-04T08:15:13.450 に答える