java 传入年月 查询本次季度和前7季度
时间: 2024-02-27 12:57:35 浏览: 24
可以使用Java中的Calendar类和SimpleDateFormat类来查询指定年月的本季度和前7个季度的日期。
以下是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
// 传入的年月
int year = 2022;
int month = 2; // 2表示3月份,因为Calendar类中月份从0开始计算
// 获取指定年月的季度
int quarter = (month / 3) + 1;
// 获取指定年月的本季度的起始日期和结束日期
Calendar calendar = Calendar.getInstance();
calendar.set(year, (quarter - 1) * 3, 1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDate = sdf.format(calendar.getTime());
calendar.set(Calendar.MONTH, (quarter - 1) * 3 + 2);
int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DATE, lastDay);
String endDate = sdf.format(calendar.getTime());
// 输出指定年月的本季度的起始日期和结束日期
System.out.println("第" + quarter + "季度:" + startDate + " - " + endDate);
// 获取指定年月前7个季度的起始日期和结束日期
for (int i = 1; i <= 7; i++) {
int tempQuarter = quarter - i;
int tempYear = year;
if (tempQuarter <= 0) {
tempQuarter += 4;
tempYear--;
}
calendar.set(tempYear, (tempQuarter - 1) * 3, 1);
startDate = sdf.format(calendar.getTime());
calendar.set(Calendar.MONTH, (tempQuarter - 1) * 3 + 2);
lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DATE, lastDay);
endDate = sdf.format(calendar.getTime());
// 输出指定年月前7个季度的起始日期和结束日期
System.out.println("第" + tempQuarter + "季度:" + startDate + " - " + endDate);
}
}
}
```
运行以上代码将会输出指定年月的本季度和前7个季度的日期,例如:
```
第1季度:2022-01-01 - 2022-03-31
第4季度:2020-10-01 - 2020-12-31
第3季度:2020-07-01 - 2020-09-30
第2季度:2020-04-01 - 2020-06-30
第1季度:2020-01-01 - 2020-03-31
第4季度:2019-10-01 - 2019-12-31
第3季度:2019-07-01 - 2019-09-30
第2季度:2019-04-01 - 2019-06-30
```