| | |
| | | return Date.from(firstDayAtMidnight.atZone(ZoneId.systemDefault()).toInstant()); |
| | | } |
| | | |
| | | /** |
| | | * 获取最近N天所有日期字符串列表 |
| | | * |
| | | * @param format 日期格式,例如 "yyyy-MM-dd" |
| | | * @param days 天数 |
| | | * @return 最近N天所有日期的字符串列表 |
| | | */ |
| | | public static List<String> getAllDatesOfLastNDays(String format, int days) { |
| | | // 当前日期 |
| | | LocalDate now = LocalDate.now(); |
| | | |
| | | // 获取N天前的日期 |
| | | LocalDate startDate = now.minusDays(days - 1); |
| | | |
| | | // 日期格式化器 |
| | | DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format); |
| | | |
| | | // 结果列表 |
| | | List<String> dates = new ArrayList<>(); |
| | | |
| | | // 从N天前到今天循环 |
| | | LocalDate currentDate = startDate; |
| | | while (!currentDate.isAfter(now)) { |
| | | dates.add(currentDate.format(formatter)); // 格式化为字符串并添加到列表 |
| | | currentDate = currentDate.plusDays(1); // 日期加一天 |
| | | } |
| | | |
| | | return dates; |
| | | } |
| | | |
| | | /** |
| | | * 获取N天前的0点时间,并返回 Date 类型 |
| | | * |
| | | * @param days 天数 |
| | | * @return N天前的0点时间(Date 类型) |
| | | */ |
| | | public static Date getFirstDayOfLastNDaysAtMidnight(int days) { |
| | | // 获取当前日期 |
| | | LocalDate now = LocalDate.now(); |
| | | |
| | | // 获取N天前的日期 |
| | | LocalDate nDaysAgo = now.minusDays(days - 1); |
| | | |
| | | // 将该天与0点时间合并 |
| | | LocalDateTime startDayAtMidnight = nDaysAgo.atTime(LocalTime.MIDNIGHT); |
| | | |
| | | // 将 LocalDateTime 转换为 Date |
| | | return Date.from(startDayAtMidnight.atZone(ZoneId.systemDefault()).toInstant()); |
| | | } |
| | | |
| | | } |