做报表的时候可能会遇到这种需求,需要列出两个时间点内的所有日期。然后再匹配数据,没有的时候展示0.
1.mysql
用sql 去处理这种业务,需要加一张临时表
//创建临时表
CREATE TABLE centre_date (i int);
INSERT INTO centre_date (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
//查询 2021-01-01 ---- 2021-03-02
SELECT
adddate( '2021-01-01', numlist.id ) AS 'date'
FROM
(
SELECT
n1.i + n10.i * 10 + n100.i * 100 AS id
FROM
centre_date n1
CROSS JOIN centre_date AS n10
CROSS JOIN centre_date AS n100
) AS numlist
WHERE
adddate( '2021-01-01', numlist.id ) < '2021-03-02'
输出结果
然后再根据业务进行关联。
2.java
//获取时间段内所有日期
LocalDate start = LocalDate.parse(startTime);
LocalDate end = LocalDate.parse(endTime);
List<String> dateList = Stream.iterate(start, localDate -> localDate.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, end) + 1)
.map(LocalDate::toString)
.collect(Collectors.toList());