按月获取星期数

时间:2019-06-24 13:04:05

标签: java

我想获取每年的星期数。这段代码有错误的结果:

for (int i = 0; i <= 11; i++) {
    Calendar cal = Calendar.getInstance(Locale.FRANCE);
    cal.set(this.anneeActuelle, i, 1);
    nombreMaxSemaine = cal.getActualMaximum(Calendar.WEEK_OF_MONTH);
}

2 个答案:

答案 0 :(得分:4)

在Java 8+中,您可以像这样使用YearMonth轻松获得每月的周数:

YearMonth.of(2019, Month.JULY).atEndOfMonth().get(WeekFields.ISO.weekOfMonth())

应避免使用旧式Calendar类(由Java 8中新的Date / Time Api代替)

答案 1 :(得分:-1)

OP希望在 MONTH 中获得最长的周数。 您可以像this

那样做
import java.util.Calendar;
import java.util.Locale;
public class App {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        if(calendar.isWeekDateSupported()) {
            Calendar cal = Calendar.getInstance(Locale.FRANCE);
            for (int i = 0; i <= 11; i++) {
                int nombreMaxSemaine = cal.getActualMaximum(Calendar.WEEK_OF_MONTH);
                System.out.println("Current week number: " + nombreMaxSemaine);
            }
        }
    }
}

输出:

Current week number: 4
Current week number: 4
Current week number: 4
Current week number: 4
Current week number: 4
Current week number: 4
Current week number: 4
Current week number: 4
Current week number: 4
Current week number: 4
Current week number: 4
Current week number: 4