Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

java - Current month count monday?

How do you find the total number of Mondays (e.g. 4 or 5) in a particular month ???

Calendar c = Calendar.getInstance();
int mon = c.getActualMaximum(Calendar.MONDAY);

is this right way ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can use this method

public int countMonday(int year, int month) {
    Calendar calendar = Calendar.getInstance();
    // Note that month is 0-based in calendar, bizarrely.
    calendar.set(year, month - 1, 1);
    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

    int count = 0;
    for (int day = 1; day <= daysInMonth; day++) {
        calendar.set(year, month - 1, day);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.MONDAY) {
            count++;
            // Or do whatever you need to with the result.
        }
    }
    return count;
}

Updated

public int countDayOccurence(int year, int month,int dayToFindCount) {
    Calendar calendar = Calendar.getInstance();
    // Note that month is 0-based in calendar, bizarrely.
    calendar.set(year, month - 1, 1);
    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

    int count = 0;
    for (int day = 1; day <= daysInMonth; day++) {
        calendar.set(year, month - 1, day);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == dayToFindCount) {
            count++;
            // Or do whatever you need to with the result.
        }
    }
    return count;
}

And then you can call this method for each day name

   int countMonday = countDayOccurence(year,month,Calendar.MONDAY);
   int countTuesday = countDayOccurence(year,month,Calendar.TUESDAY);

...............................................


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...