public Date getFirstDay(int year, int month) {
// 获取Calendar类的实例
Calendar c = Calendar.getInstance();
// 设置年份
c.set(Calendar.YEAR, year);
// 设置月份,因为月份从0开始,所以用month - 1
c.set(Calendar.MONTH, month - 1);
// 设置日期
c.set(Calendar.DAY_OF_MONTH, 1);
return c.getTime();
}
public Date getLastDay(int year, int month) {
// 获取Calendar类的实例
Calendar c = Calendar.getInstance();
// 设置年份
c.set(Calendar.YEAR, year);
// 设置月份,因为月份从0开始,所以用month - 1
c.set(Calendar.MONTH, month - 1);
// 获取当前时间下,该月的最大日期的数字
int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
// 将获取的最大日期数设置为Calendar实例的日期数
c.set(Calendar.DAY_OF_MONTH, lastDay);
return c.getTime();
}
- 调用函数
int year = 2022;
int month = 08;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String firstDay = format.format(getFirstDay(year, month)) + " 00:00:00";
String lastDay = format.format(getLastDay(year, month)) + " 23:59:59";
标签:set,第一天,format,int,month,获取,日期,year,Calendar
From: https://www.cnblogs.com/liguiping/p/16594067.html