获取2个时间戳之间的日期

获取2个时间戳之间的日期

    /**
     * 根据索引前缀、 from和 to生成需要查询的ES索引
     * 以查询 monitor索引为例:generateIndexStringFromRange("delta-monitor-", from, to)
     * 返回值示例: delta-monitor-2023.09.13,delta-monitor-2023.09.14
     */
    public static String generateIndexStringFromRange(String indexPattern, Long from, Long to){
        if (from == null || to == null) {
            throw new IllegalArgumentException("起始时间from或结束时间to不能为null");
        }

        return buildIndexStringFromDates(generateDateListFromEpochMilliRange(from, to), indexPattern);
    }

    public static String buildIndexStringFromDates(List<String> dateList, String indexPattern) {
        if (CollectionUtils.isEmpty(dateList)){
            return "";
        }

        StringBuilder indexRangeBuilder = new StringBuilder();

        for (String s : dateList) {
            indexRangeBuilder.append(indexPattern).append(s).append(",");
        }
        return indexRangeBuilder.deleteCharAt(indexRangeBuilder.length() - 1).toString();
    }

    /**
     * 返回值 ["2023.09.13", "2023.09.14"]
     */
    public static List<String> generateDateListFromEpochMilliRange(Long from, Long to) {
        List<String> dateDetails = new ArrayList<>();

        LocalDate startDate = Instant.ofEpochMilli(from).atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endDate = Instant.ofEpochMilli(to).atZone(ZoneId.systemDefault()).toLocalDate();

        // 循环遍历日期并输出
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            dateDetails.add(currentDate.toString().replace("-", "."));
            currentDate = currentDate.plusDays(1);
        }

        return dateDetails;
    }
posted @ 2023-12-15 11:29  SpecialSpeculator  阅读(18)  评论(0编辑  收藏  举报