Java 根据年月 获取当月最后一天
作者:互联网
public class LastDayOfMonth
{
/**
* 获取某月的最后一天
*
*/
public static String getLastDayOfMonth(int year,int month)
{
Calendar cal = Calendar.getInstance();
//设置年份
cal.set(Calendar.YEAR,year);
//设置月份
cal.set(Calendar.MONTH, month-1);
//获取某月最大天数
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
//设置日历中月份的最大天数
cal.set(Calendar.DAY_OF_MONTH, lastDay);
//格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String lastDayOfMonth = sdf.format(cal.getTime());
return lastDayOfMonth;
}
/**
* main
*/
public static void main(String[] args)
{
String lastDay = getLastDayOfMonth(2021,7);
System.out.println("获取当前月的最后一天:" + lastDay);
//获取当前月的最后一天:2021-07-31
}
}
标签:set,Java,String,int,获取,当月,cal,lastDay,Calendar 来源: https://blog.csdn.net/qq_36636312/article/details/118608638