1、先放一个自己写的
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份,enter结束: ");
int year = Integer.parseInt(sc.nextLine());
//判断当前年份是否为闰年
boolean isLeapYear = false;
if( year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ){
isLeapYear = true;
}
//循环月份
for (int month = 1; month <= 12; month++) {
//判断月份中的天数
int numberOfDays = 30;
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
numberOfDays = 31;
}
//2月-闰年29天,非闰年28天
if(month == 2 && isLeapYear) {
numberOfDays = 29;
}else {
numberOfDays = 28;
}
}
2、这是其他同学用的工具类写的示例
package net.wanghe.demo01;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Demo01 {
public static void main(String[] args) {
System.out.println(getMonthDays(2021, 2));
System.out.println(getMonthDays("202102"));
}
public static int getMonthDays(int year, int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, (month - 1));
cal.set(Calendar.DATE, 1);
cal.roll(Calendar.DATE, -1);
return cal.getActualMaximum(Calendar.DATE);
}
public static int getMonthDays(String yearMonth) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(sdf.parse(yearMonth));
} catch (ParseException e) {
e.printStackTrace();
}
calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}
以上示例转自:https://blog.csdn.net/weixin_43479686/article/details/117390010



