protected static List<String> getTimePeriodFromTwoTime(Long startTime, Long endTime, TimeTypeEnum typeEnum) {
LocalDate start = Instant.ofEpochMilli(startTime).atZone(ZoneOffset.ofHours(8)).toLocalDate();
LocalDate end = Instant.ofEpochMilli(endTime).atZone(ZoneOffset.ofHours(8)).toLocalDate();
List<String> result = new ArrayList<>();
if (typeEnum.getType().equals(TimeTypeEnum.YEAR.getType())) {
Year startyear = Year.from(start);
Year endYear = Year.from(end);
for (long i = 0; i <= ChronoUnit.YEARS.between(startyear, endYear); i++) {
result.add(startyear.plusYears(i).toString());
}
}
else if (TimeTypeEnum.MONTH.getType().equals(typeEnum.getType())) {
YearMonth from = YearMonth.from(start);
YearMonth to = YearMonth.from(end);
for (long i = 0; i <= ChronoUnit.MONTHS.between(from, to); i++) {
result.add(from.plusMonths(i).toString());
}
}
else {
for (long i = 0; i <= ChronoUnit.DAYS.between(start, end); i++) {
result.add(start.plus(i, ChronoUnit.DAYS).toString());
}
}
return result;
}
获取两个时间之间的日期
public static void main(String[] args) {
LocalDate start = LocalDate.of(2022, 1, 1);
LocalDate end = LocalDate.of(2022, 1, 15);
long timstrap = start.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
long endtime = end.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
for (String s : getTimePeriodFromTwoTime(timstrap, endtime, TimeTypeEnum.DAY)) {
System.out.println(s);
}
}
2022-01-01
2022-01-02
2022-01-03
2022-01-04
2022-01-05
2022-01-06
2022-01-07
2022-01-08
2022-01-09
2022-01-10
2022-01-11
2022-01-12
2022-01-13
2022-01-14
2022-01-15
获取两个时间之间的月份
public static void main(String[] args) {
LocalDate start = LocalDate.of(2022, 1, 1);
LocalDate end = LocalDate.of(2022, 5, 31);
long timstrap = start.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
long endtime = end.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
for (String s : getTimePeriodFromTwoTime(timstrap, endtime, TimeTypeEnum.MONTH)) {
System.out.println(s);
}
}
2022-01
2022-02
2022-03
2022-04
2022-05
获取两个时间之间的年份
public static void main(String[] args) {
LocalDate start = LocalDate.of(2016, 1, 1);
LocalDate end = LocalDate.of(2022, 3, 31);
long timstrap = start.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
long endtime = end.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
for (String s : getTimePeriodFromTwoTime(timstrap, endtime, TimeTypeEnum.YEAR)) {
System.out.println(s);
}
}
2016
2017
2018
2019
2020
2021
2022
|