获取当前季度,根据月转换到季度:
public static int getQuarterOfYear() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
return calendar.get(Calendar.MONTH) / 3 + 1;
}
根据季度获取第一天,从季度到第一个月,再到月的第一天
public static Date getStartDayOfQuarter(int year, int quarter) {
int startMonth = (quarter - 1) * 3;
// 根据月获取开始时间
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, startMonth);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
根据季度获取最后一天,从季度到最后一个月,再到月的最后一天
public static Date getLastDayOfQuarter(int year, int quarter) {
int lastMonth = quarter * 3 - 1;
// 根据月获取开始时间
// 根据月获取开始时间
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, lastMonth);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
测试代码:
public static void main(String[] args) {
Date startDayOfQuarter = getStartDayOfQuarter(2022, 1);
System.out.println("startDayOfQuarter = " + startDayOfQuarter);
Date lastDayOfQuarter = getLastDayOfQuarter(2022, 1);
System.out.println("lastDayOfQuarter = " + lastDayOfQuarter);
}