java 获取当前时间的前后四个季度
时间: 2024-01-14 11:21:33 浏览: 187
在Java中,可以使用`java.time.LocalDate`类来获取当前时间的前后四个季度。下面是一个示例代码:
```java
import java.time.LocalDate;
import java.time.Month;
public class Demo {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
int currentYear = today.getYear();
Month currentMonth = today.getMonth();
int currentQuarter = (currentMonth.getValue() - 1) / 3 + 1;
// 获取前四个季度
for (int i = currentQuarter - 4; i < currentQuarter; i++) {
int year = currentYear;
int quarter = i;
if (quarter <= 0) {
year--;
quarter += 4;
}
LocalDate startDate = LocalDate.of(year, (quarter - 1) * 3 + 1, 1);
LocalDate endDate = startDate.plusMonths(3).minusDays(1);
System.out.println("第" + quarter + "季度:" + startDate + " - " + endDate);
}
// 获取后四个季度
for (int i = currentQuarter + 1; i <= currentQuarter + 4; i++) {
int year = currentYear;
int quarter = i;
if (quarter > 4) {
year++;
quarter -= 4;
}
LocalDate startDate = LocalDate.of(year, (quarter - 1) * 3 + 1, 1);
LocalDate endDate = startDate.plusMonths(3).minusDays(1);
System.out.println("第" + quarter + "季度:" + startDate + " - " + endDate);
}
}
}
```
这段代码首先获取当前日期的年份和月份,然后根据当前月份计算当前季度。接下来,使用循环分别计算前四个季度和后四个季度的起始日期和结束日期,并打印输出。
阅读全文