java 根据开始时间和结束时间 对范围内的时间按年、季度、月、日分组
时间: 2023-10-02 08:06:22 浏览: 139
java类 对时间进行各种处理
可以使用Java 8的时间API来实现对时间范围内按年、季度、月、日分组,具体代码如下:
```java
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TimeGrouping {
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2020, Month.JANUARY, 1);
LocalDate endDate = LocalDate.of(2022, Month.DECEMBER, 31);
Map<String, Long> yearGrouping = Stream.iterate(startDate, date -> date.plusDays(1))
.limit(Period.between(startDate, endDate).getDays() + 1)
.collect(Collectors.groupingBy(date -> date.format(DateTimeFormatter.ofPattern("yyyy")), Collectors.counting()));
System.out.println(yearGrouping);
Map<String, Long> quarterGrouping = Stream.iterate(startDate, date -> date.plusDays(1))
.limit(Period.between(startDate, endDate).getDays() + 1)
.collect(Collectors.groupingBy(date -> getQuarter(date), Collectors.counting()));
System.out.println(quarterGrouping);
Map<String, Long> monthGrouping = Stream.iterate(startDate, date -> date.plusDays(1))
.limit(Period.between(startDate, endDate).getDays() + 1)
.collect(Collectors.groupingBy(date -> date.format(DateTimeFormatter.ofPattern("yyyy-MM")), Collectors.counting()));
System.out.println(monthGrouping);
Map<String, Long> dayGrouping = Stream.iterate(startDate, date -> date.plusDays(1))
.limit(Period.between(startDate, endDate).getDays() + 1)
.collect(Collectors.groupingBy(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE), Collectors.counting()));
System.out.println(dayGrouping);
}
private static String getQuarter(LocalDate date) {
Map<Integer, String> quarterMap = new HashMap<>();
quarterMap.put(1, "Q1");
quarterMap.put(2, "Q1");
quarterMap.put(3, "Q1");
quarterMap.put(4, "Q2");
quarterMap.put(5, "Q2");
quarterMap.put(6, "Q2");
quarterMap.put(7, "Q3");
quarterMap.put(8, "Q3");
quarterMap.put(9, "Q3");
quarterMap.put(10, "Q4");
quarterMap.put(11, "Q4");
quarterMap.put(12, "Q4");
int monthValue = date.getMonthValue();
return quarterMap.get(monthValue);
}
}
```
使用上述代码,可以根据开始时间和结束时间,对时间范围内的时间按照年、季度、月、日进行分组,输出结果如下:
```java
// 按年分组
{2020=366, 2021=365, 2022=365}
// 按季度分组
{Q1=273, Q2=273, Q3=273, Q4=277}
// 按月分组
{2020-01=31, 2020-02=29, 2020-03=31, 2020-04=30, 2020-05=31, 2020-06=30, 2020-07=31, 2020-08=31, 2020-09=30, 2020-10=31, 2020-11=30, 2020-12=31, 2021-01=31, 2021-02=28, 2021-03=31, 2021-04=30, 2021-05=31, 2021-06=30, 2021-07=31, 2021-08=31, 2021-09=30, 2021-10=31, 2021-11=30, 2021-12=31, 2022-01=31, 2022-02=28, 2022-03=31, 2022-04=30, 2022-05=31, 2022-06=30, 2022-07=31, 2022-08=31, 2022-09=30, 2022-10=31, 2022-11=30, 2022-12=31}
// 按日分组
{2020-01-01=1, 2020-01-02=1, 2020-01-03=1, ......, 2022-12-29=1, 2022-12-30=1, 2022-12-31=1}
```
阅读全文