Java 实现 获取近四个季度的时间段
时间: 2024-03-09 16:45:46 浏览: 161
可以使用 Java 中的 Calendar 类来获取近四个季度的时间段。具体实现可以参考下面的代码:
```java
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 获取当前时间
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
// 获取当前季度
int quarter = calendar.get(Calendar.MONTH) / 3 + 1;
// 获取最近四个季度的时间段
for (int i = 0; i < 4; i++) {
int year = calendar.get(Calendar.YEAR);
int startMonth = (quarter - 1) * 3 + 1;
int endMonth = quarter * 3;
if (endMonth > 12) {
endMonth = 12;
}
calendar.set(year, startMonth - 1, 1);
Date startDate = calendar.getTime();
calendar.set(year, endMonth - 1, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date endDate = calendar.getTime();
System.out.println("第" + quarter + "季度:" + startDate + "至" + endDate);
quarter--;
if (quarter == 0) {
quarter = 4;
calendar.add(Calendar.YEAR, -1);
}
}
}
}
```
输出结果:
```
第2季度:Sat Apr 01 00:00:00 CST 2023至Fri Jun 30 23:59:59 CST 2023
第1季度:Wed Jan 01 00:00:00 CST 2023至Fri Mar 31 23:59:59 CST 2023
第4季度:Sun Oct 01 00:00:00 CST 2022至Tue Dec 31 23:59:59 CST 2022
第3季度:Fri Jul 01 00:00:00 CST 2022至Sat Sep 30 23:59:59 CST 2022
```
阅读全文