Java获取指定月份的天数

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);
	}
	
}
上一篇:Java常用API


下一篇:Java 根据年月 获取当月最后一天